Multilanguage's Sitemap, get_absolute_url and location
Plz help me with the correct Sitemap generation. My multilanguage site on Django 2.2 with standard internationalization framework.
Model.py with get_absolute_url
class Data(models.Model):
...
def get_absolute_url(self):
from django.urls import reverse
return reverse("data_detail", kwargs={"slug": str(self.id)})
Sitemap.py
class DataSitemap (Sitemap):
changefreq = "daily"
priority = 0.5
i18n = True
def items(self):
return Data.objects.all()
def location(self, obj):
return '/news/data/%s/' % (obj.pk)
url.py
from django.contrib.sitemaps.views import sitemap
from .sitemaps import DataSitemap
sitemaps = {
'data' : DataSitemap
}
urlpatterns = i18n_patterns(
path("sitemap.xml", sitemap, {"sitemaps": sitemaps},
name='django.contrib.sitemaps.views'),
)
Now when I generate sitemap.xml I get no language prefix,
<url>
<loc>example.com/news/data/1/</loc>
<lastmod>2022-03-24</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>example.com/news/data/1/</loc>
<lastmod>2022-01-08</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
For the other Model without with get_absolute_url but without harcoded location - everything works fine, language prefix added correctly.
How can I fix my Sitemap code?
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
Upload file from html when block public access is true
I am using
django-s3direct
to file uploadhttps://github.com/bradleyg/django-s3direct
Using IAM role setting because I upload the file from the server on ECS container.
Now I set the
blockPublicAccess
ofS3
false.When uploading images from html, there comes error.
https://s3.ap-northeast-1.amazonaws.com/static-resource-v/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg?uploads (403 (Forbidden) ) initiate error: static-resource-v/line-assets/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg AWS Code: AccessDenied, Message:Access Deniedstatus:403
OK, it is understandable.
Browser try to access the for initiation.
However there is any way to upload file from browser when blockPublicAccess is true??
-
Test a decorated function in Python
I have a python function which is decorated.
@retry_if_access_token_expired(app_id) def add_something( self, *, argument1, argument1 = None, ): """adding something"""
I've written tests for the given as below.
@patch("other inside function to mock") @patch("other insdie function to mock 2") def test_add_something( self, mock_1, mock_2 ): """ some logic to test the add something method """
But I am getting this error that says add_somehthing takes 1 positional argument.
TypeError: add_something() takes 1 positional argument but 3 were given
-
how to pass null value to just one specific key of the one object using same DRF serializer
I'm just passing the same object 2 times in the same serializer but I want to pass key: "retweet": null in one object and in another object I want to pass some values like some many-to-many field values because key "retweet" is many-to-many field and having data
Thanks in advance!
-
Swing JFrame rendering a webpage with embedded video shows a white page and throws IOException with "invalid URL"
I wonder if I do some mistakes because I do not get the content of the webpage displayed on the
JFrame
. Instead, I only get a white page. The error I got was:java.io.IOException: invalid URL
Here is the code for
video.html
:<iframe width="560" height="315" src="video-file.mp4" allowfullscreen></iframe>
Thanks in advance for any help!
import java.awt.*; import java.io.IOException; import java.net.URL; import javax.swing.*; public class Vid extends JFrame{ public Vid(String title){ super(title); setBounds(100, 100, 550, 500); Container ControlHost = getContentPane(); ControlHost.setLayout(new FlowLayout()); JEditorPane jep = new JEditorPane(); jep.setEditable(false); JScrollPane scroll = new JScrollPane(jep); Dimension ScrollSize = new Dimension(500, 450); scroll.setPreferredSize(ScrollSize); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); ControlHost.add(scroll); URL HtmlPage = Vid.class.getResource("video.html"); try { jep.setPage(HtmlPage); } catch (IOException ex) { ex.printStackTrace(); } } }
-
How do i connect to websocket URL from website?
i'm trying to get the update values from website, i manage to connect but i cant get the values, i dont know if i'm doing anything wrong.
this is what i'm trying to do, maybe this url is not complete, but i dont know how to get the full URL. when i try to conect i dont recieve anything, i read the coments i will try to send something to this websocket
you need click in this button to show the entry hall
const WebSocket = require('ws') const ws = new WebSocket('wss://eurolive-frontend.playtechgaming.com/ws') ws.onmessage = (event) =>{ console.log(event.data) } ws.onerror = (erro)=>{ console.log(erro) }```
-
Download and Install .apk file form URL programmatically
I want to make a App which is downloading the .apk file from GitHub and installing it at once.
-
Updating the template when an active child route is changed inside a lazy module
I have this component bellow:
Where "OPERATIONS" is the parent component, considered as a view, and the others are sub-views.
Each sub-view could redirect to a new route under the view OPERATIONS, the corresponding component of subview is loaded in the same page inside the operations view where I added my router-outlet.
I want to add a default style for active sub-view basing on the active route (orange background), but the problem is that the view operations is loaded lazily (lazy loading) so when I try to read the url of the active route I'm just getting the url of the parent route before having the whole URL of the sub-view too.
In the html template I'm doing this:
<div class="operations-menu" style="background-color: #121212;"> <li style="padding-bottom: 0%;margin-bottom: 0%;"> <a class="padding-left" #operations data-toggle="collapse" data-target="#operations-menu-content" role="button" aria-expanded="true" aria-controls="operations-menu-content"> OPERATIONS</a> </li> <ul style="background-color: #101010;" class="collapse show" id="operations-menu-content"> <div (click)="redirectToSubView(subview)" *ngFor="let subview of getAllSubViewsOfOperationsFromToken()"> <li *ngIf="isActiveSubView(subview)" class="padding-left-menu-item active-sub-view"> {{subview}} </li> <li *ngIf="!(isActiveSubView(subview))" class="padding-left-menu-item"> {{subview}} </li> </div> </ul> </div>
In the isActiveSubView() function I want to detect if the sub-view match the active sub-route in the url, so I did this:
isActiveSubView(subView: string) { return subView == this.activeSubView ? true : false; }
the variable activeSubView is being assigned in the function bellow:
checkActiveViewAndStyle() { if (this.router.url.includes('/operation')) { this.renderer2.addClass(this.operationsMenuItem.nativeElement, 'active') } if (this.router.url.includes('/finv')) { this.activeSubView = "FINV"; } }
The above function I call it inside ngAfterViewInit():
ngAfterViewInit(): void { //wait for lazy loading to be done then check setTimeout(() => { this.checkActiveViewAndStyle(); }, 200) }
Note that when the component OPERATIONS is loaded lazily, I'm after that doing a redirection to a default sub-view:
ngOnInit(): void { //redirect to a default sub-view inside the operations view this.manageRedirection(); }
Now I'm looking for a way to update the style whenever I change the value of the variable activeSubView
-
In a C# ASP.NET Core 3.1 application how do I route to a controller then query string?
I have a view setup as:
I then have my Business controller:
[Route("{business}/{url}")] public IActionResult business(string url) { return View(); }
My aim is to be able to pass the url string 'neatly' like so
https://website.com/business/business-name-123
The
business-name-123
is then received as the parameter.I have created something similar to this before where you pass
?query=website-name
but I don't want this, can someone explain what I need to do to get this working using just the / routing aspect? -
application doesn't update language after changing the phone's language
i have created a simple xamarin.forms app in order to learn how to make my app multilingual. i found this tutorial https://www.c-sharpcorner.com/article/support-multiple-languages-in-xamarin-forms-application/ and applied it. the thing is, when i debug the app when my phone's language is english, the button's text is "click me". but when i change the phone's language to arabic, the text's language doesn't change unless i rerun the app all over again from my visual studio. so if i open the app normally from my phone the language doesn't change even if i change my phone's language. this is my code:
mainpage.xaml.cs
public MainPage() { InitializeComponent(); btn.Text = ApplicationResource.btntxt; }
mainpage.xaml
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="App1.MainPage"> <StackLayout> <Button Clicked="Button_Clicked" x:Name="btn"/> </StackLayout> </ContentPage>
-
What Unicode Ranges are used exclusively by Simplified Chinese, Traditional Chinese, Korean, and Japanese?
I need to create packages that contain Unicode characters used only by a specified language. A key requirement for these packages is to make them as small as possible (thus why each package only contains the characters used for its language).
The problem is I can't find a single resource online that specifies the ranges ONLY for a certain language, such as ranges X1-X2, Y3-Y8, etc for Simplified Chinese. Instead everywhere tells me to use CJK (U+4E00 - U+9FFF). I'd like to know which parts of CJK are used for each of the below languages.
I understand that many characters in Asian languages are considered obsolete/unused. Thus they should be excluded from the ranges. The ranges should only include characters used to communicate. I hope that's clear haha..
That being said, the languages I'm try to make these packages for are:
- Simplified Chinese
- Traditional Chinese
- Korean
- Japanese
Does anyone know the exclusive ranges for these languages or how to find them out?
-
Calculating sematic similarity between pairs of words that is comparable between different languages - which ressources/vectors/corpora are suitable?
Short background: I am looking for a way to quantify how similar pairs of interlingual homographs (words that are written the same in multiple languages) are in two languages of my interest, idealy by using cosine similarity as a measure. Therefor, it's important to me, that the measure is comparable across languages. Besides that, I am looking for a semi-automatic way to find words with very unambigous translations between two languages (e.g. possibly something like april, monday, black, pineapple, aunt etc. which are already quite monosemious in one language).
I discovered fasttext, specifically the aligend vectors, which I downloaded in two languages. However, the single vectors of each word in those files are rather small, so if I'm trying to calculate cosine similarity (formula: (AxB)/(|A|x|B|) with A being the vector of word A in one language and B the vector of another word B in the same language), I naturally receive only 1 or -1, which isn't going to help me with my problem of measuring how similar those two words are in terms of meaning as only two possible numbers as a result aren't that informative. I'm unsure now, wether I can just calculate cosine similarity based on nonaligend vectors (of a different ressoruce) and still receive a measure that is comparable across different languages, if I calculate cosine similarity for pairs of interlingual homographs within each language that interests my?
Secondly, I was hoping that aligned vectors of similar value in two languages might belong to translation equivalents, but just by looking at the words/data of the two aligend vector files that I downloaded, but that doesn't seem to be the case. Can you think of any other way than those aligned vectors that might be of use to me by trying to find unambigous translation equivalents of two languages?
My question now is: is fasttext per se suitable (I had high hopes) and I'm just approaching it incorrectly or am I completely on the wrong track and I need to find another ressource? Any recommendations are highly appreciated of what that ressources may look like or where it can be found. (I'm quite new to this whole field).