Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Sub Filter Brings Same Datas with Main Filter
I am making very simple business directory. I wanna display a list of firms that belong to a particular city and district, and belong to a certain category. But district filter and city filter brings same datas. How can i fix this? I filtered to district but again brings main city datas. Where is my fault? models.py class City(models.Model): city = models.CharField(max_length=50) slug = models.SlugField() def __str__(self): return str(self.city) class District(models.Model): district = models.CharField(max_length=50) slug = models.SlugField() city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return str(self.district) class FirmaCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() class Meta: verbose_name_plural = 'Firma Kategorileri' def __str__(self): return str(self.title) class Firma(models.Model): category = models.ForeignKey(FirmaCategory, related_name="Firma", on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() adres = tinymce_models.HTMLField() tel = tinymce_models.HTMLField() website = tinymce_models.HTMLField() email = tinymce_models.HTMLField() intro = tinymce_models.HTMLField() body = tinymce_models.HTMLField() city = models.ForeignKey(City,related_name="FirmaCategory" ,on_delete=models.CASCADE) district = models.ForeignKey(District,related_name="FirmaCategory", on_delete=models.CASCADE) #url = models.CharField(max_length=255) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Firmalar' def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('firma-frontpage') views.py def firmaana(request): firmalar = Firma.objects.all() context = { 'firmalar': firmalar } return render(request, 'firma/firma-frontpage.html', context) def firmadetail(request, slug): firmax = Firma.objects.get(slug=slug) context = { 'firmax': firmax, } return render(request, 'firma/firma-detail.html', context) def firmacategory(request, slug): firmacategory = FirmaCategory.objects.get(slug=slug) context … -
Can't download working dxf file generated by ezdxf from django server
Generated dxf file (ezdxf) from django server using below code: bio = io.StringIO() document.write(bio) # save to memory stream length = bio.tell() bio.seek(0) # rewind the stream response = HttpResponse( bio.getvalue(), # use the stream's contents content_type="image/x-dxf", ) response["Content-Disposition"] = 'attachment; filename = {0}'.format(cab.split(' ')[1] + ".dxf") response["Content-Encoding"] = "UTF-8" response['Content-Length'] = length return response is missing the last few lines, including the EOF line. Compared to a dxf file obtained simply by document.save() What needs to be added to the code so that the downloaded dxf file is identical to the saved dxf file? -
WebSocket django channels doesn't work with postman
Django Channels Throw error with postman while working well with Html. I'm following Django Socket Tutorial "here's the error showing in Django". WebSocket HANDSHAKING /ws/chat/roomName/ [127.0.0.1:56504] WebSocket REJECT /ws/chat/roomName/ [127.0.0.1:56504] WebSocket DISCONNECT /ws/chat/roomName/ [127.0.0.1:56504] "Error showing in postman when connecting to ws://127.0.0.1:8000/ws/chat/roomName/" Sec-WebSocket-Version: 13 Sec-WebSocket-Key: fSSuMD2QozIrgywqTX38/A== Connection: Upgrade Upgrade: websocket Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits Host: 127.0.0.1:8000 My Code asgi.py django_asgi_app = get_asgi_application() import digital_signage.playlist_management.routing application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(digital_signage.playlist_management.routing.websocket_urlpatterns)) ), } ) consumer.py class ChatConsumer(WebsocketConsumer): def connect(self): print("self", self) self.accept() -
Switching from LDAP to AD LDAPS using Python Django
Converting authentication from LDAP to AD LDAPS Python + Django ============== Following Django Docs: https://django-auth-ldap.readthedocs.io/en/latest/authentication.html OLD: AUTH_LDAP_SERVER_URI = "ldap://ldap-example.test.com" NEW: AUTH_LDAP_SERVER_URI = "ldaps://ad.example.com" ============== I have worked with the AD administrator to set these values correctly. I changed the values themselves for obvious privacy reasons. AUTH_LDAP_BIND_DN = "cn=ex-test,cn=user,dc=test,dc=ad" AUTH_LDAP_BIND_PASSWORD = "{PASSWORD}" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=sites,dc=test,dc=ad",ldap.SCOPE_SUBTREE,"(uid=%(user)s)") AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS: 0} AUTH_LDAP_USER_DN_TEMPLATE = "cn=%(user)s,ou=sites,dc=test,dc=ad" AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_GROUP_SEARCH = LDAPSearch("cn=priv-ex,ou=due,ou=ldap,ou=shared,dc=test,dc=ad", ldap.SCOPE_SUBTREE) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn') AUTH_LDAP_USER_ATTR_MAP = { "first_name": "usersName", "last_name": "usersLastName", "email": "usersEmail" } AUTH_LDAP_REQUIRE_GROUP = "cn=DUE-MAIN,ou=DUE,ou=Applications,ou=Sharing,o=LDAP" ============== Problem It will not work for login. I do not know what I am doing wrong as I am following the docs precisely. Questions Q1: Is there anyway I can test the connection from a terminal or command line? Q2: I have seen the django-pyad package recommened with a settings.py that looks like # settings.py AUTHENTICATION_BACKENDS = [ 'django_pyad.backend.ADBackend', ] # AD configuration AD_LDAP_SERVER = "ad.example.com" AD_NT4_DOMAIN = "example" AD_SEARCH_DN = "OU=Users,DC=ad,DC=example,DC=com" Should I scrap what I did for the previous LDAP tree and go this route instead? Or can I re-use the previous LDAP connection code but change the values for AD like I am doing now? -
How to store data typed by user into input using Django
Im kinda new to django and i got stuck I want to get user input, and after that i want to display value which depend on it For example in djanog i have if statment which checking input from user, for exaple car model. So, when user type Ibiza i want to display "Seat", user type E92 i want to dispaly "BMW" etc I want to display car brands in list which can be cleard or dissapear after user close tab and re-open. Which solution is the best? Database in django? Cookies? Local storage in javascript? -
Mod_wsgi server will not start up
I am moving a currently working Django project to a new Red Hat server and upon moving the project, it's virtual env, and installing pip packages I started up the server how I always have and it worked fine. Going back to it a week later I enter in the web address of the django site and it times out. The mod_wsgi error log reads. [Tue Dec 20 17:55:49.282343 2022] [core:warn] [pid 831143:tid 139775964862784] AH00098: pid file /tmp/mod_wsgi-localhost:8080:21056/httpd.pid overwritten -- Unclean shutdown of previous Apache run? [Tue Dec 20 17:55:49.283800 2022] [mpm_event:notice] [pid 831143:tid 139775964862784] AH00489: Apache/2.4.37 (Red Hat Enterprise Linux) mod_wsgi/4.9.4 Python/3.6 configured -- resuming normal operations [Tue Dec 20 17:55:49.283823 2022] [core:notice] [pid 831143:tid 139775964862784] AH00094: Command line: 'httpd (mod_wsgi-express) -f /tmp/mod_wsgi-localhost:8080:21056/httpd.conf -D MOD_WSGI_KEEP_ALIVE -D MOD_WSGI_MPM_ENABLE_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_WORKER_MODULE -D MOD_WSGI_MPM_EXISTS_PREFORK_MODULE -D FOREGROUND' I can't figure out what this error indicates is happening. httpd.pid overwritten -- Unclean shutdown of previous Apache run? I've even restarted the apache server that runs on this server and it has done nothing. -
Getting data from another Foreign key - DRF
The relations of tables are shown in the picture. I have a main Table named Product. Two tables ProductImage , OrderedProduct have a Foreign key set to it. Now, I want to retrieve the image from OrderedProduct. How should I write the code for Serialization for it? Thanks Models.py Visualization This is my model.py file: class Product(models.Model): name = models.CharField(max_length=50) description = models.TextField() def __str__(self) -> str: return self.name class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='product_images') image = models.ImageField(upload_to="images/", null=True, blank=True) class OrderedProduct(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='ordered_products') quantity = models.IntegerField() Serializers.py class OrderedProductSerializer(serializers.ModelSerializer): product_name = serializers.CharField(source='product.name') product_price = serializers.FloatField(source='product.price') # product_img = >>> what should I do here? <<< class Meta: model = OrderedProduct fields = ('user', 'product', 'quantity', 'delivered', 'product_name', 'product_price', 'product_img') I've read the documentation, asked in some programming groups but couldn't find any good solution. I am expecting someone to give a reference that leads to the solution. -
How to upload an image to django from an html input file
I am developing a web service on django with frontend on react. I ran into a problem that I can't upload an image to django. Below is my component code where I'm trying to download it: export function ProviderRegistration(){ const[logoField, setLogoField] = useState() const token = useSelector((state) => state.user.token) const [cookie, setCookie] = useCookies(['auth']) const confirm = () => { axios.post(`/providers/?username=${cookie.auth.login}`, { photo : logoField }, { "headers" : { "Authorization" : "token " + token }}) .then(res => console.log(res)) .catch(err => console.log(err)) } return( <div className="registration-provider-container"> <div className="registration-title">Provider registration</div> <input type="file" className="registration-logo-add" onChange={(e) => setLogoField(e.target.value)}/> <button className="registration-confirm" onClick={() => confirm()}>Confirm</button> </div> )} And the endpoint processing this request class Providers(viewsets.ModelViewSet): filterset_class = ProvidersFilter queryset = Provider.objects.all() permission_classes = [IsAuthenticatedOrReadOnly, IsProviderPermission, IsOneToOneProviderPermission] def get_serializer_class(self): if self.action == 'list': return GetProviderSerializer else: return PutProviderSerializer def create(self, request): username = request.GET.get('username', '') user = User.objects.get(username=username).pk request.data.update({'user' : user}) print(request.data) return super().create(request) When I try to upload an image, django returns the following error: "The submitted data was not a file. Check the encoding type on the form." And I haven't found a way to correctly upload an image to django using Ajax. I also output what my browser sends to the server: … -
Using Model.objects.filter in Form prevents me from updating Model
I have a form setup like this where I use the values from TestModel to create a select field in a form. However if I want to update the TestModel to add a new column, Django gives me a psycopg2.errors.UndefinedColumn saying the new column is not found on the table and the stack trace points back to this form ModelChoiceField. Its not until I comment out this select that I am able to make the migration to the database. So my question is there a better way to setup this ModelChoiceField where I don't have to comment it out to update the underlying model on the database? I'm using Django 4.0 and python 3.8 for reference. class TestModelChoiceField(forms.ModelChoiceField): """ Overwriting model choice field attribute to use a different __str__ representation than the default model """ def label_from_instance(self, obj): return obj.test_field class TestForm(forms.Form): first_select = TestModelChoiceField( queryset=TestModel.objects.filter(model_attribute__isnull=False), initial=TestModel.objects.filter(model_attribute__isnull=False) .filter(test_field="Yes") .first() .team_id, label="Field One:", ) -
Creating a simple multiple users app in Django
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and log out, it works, but then I when try to use the login form, it seems to me that it's acting like the signup form. Because when I input the same user details as the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here. Here's what I have so far. models.py class CustomUser(AbstractUser): ACCOUNT_TYPE_CHOICES = ( ('admin', 'Admin'), ('developer', 'Developer'), ('project_manager', 'Project Manager') ) account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES) login and signupviews class LoginView(View): def get(self, request): # Render the login form form = LoginForm() return render(request, 'users/login.html', {'form': form}) def post(self, request): # Get the form data from the request form = LoginForm(request.POST) # Validate the form data if form.is_valid(): # Get the username and password from the form username = form.cleaned_data['username'] password = form.cleaned_data['password'] # Authenticate the user user = authenticate(request, username=username, password=password) # If the user is authenticated, log them in and redirect to the homepage if user is not None: login(request, … -
How to show print diagloue box in browser in Django?
I am trying to get the print dialogue box in my Django app. Currently its downloading in my local computer. But when I am serving in apache server, its not working. my views.py def download(request,lothash): lot=lotnumber.objects.get(lot_hash=lothash) postdata = request.POST array = postdata.get("array", None).split(",") template=lot.template_type f = open(f"/home/username/public_html/nitin2/media/{template.template_file}", "r") txt=(f.read()) df=pd.read_excel("/home/username/public_html/nitin2/media/"+str(lot.file)) df = df.reset_index() n=1 k=0 for index, row in df.iterrows(): if n>len(array)+1: break if str(n) in array: txt = txt.replace("(As Provided by Bank)", str(row['RGN_A'])) txt = txt.replace("(Customer Name)", str(row['Applicant Name'])) txt = txt.replace("(Customer Address)", str(str(row['Address1']) + " " + str(row['Address2']) + " " + str(row['Address3']))) txt = txt.replace("(Product)", str(row['Product'])) txt = txt.replace("(LAN)", str(row['LAN'])) txt = txt.replace("(Notice Amount)", str(row['Notice Amount'])) # save FPDF() class into a # variable pdf pdf = FPDF() # Add a page pdf.add_page() # set style and size of font # that you want in the pdf pdf.set_font("Arial", size = 12) # insert the texts in pdf newtxt=splitlinesoftext(txt) for x in newtxt: pdf.multi_cell(0, 5, txt = x, align = 'L',border=0) downloads_path = str(Path('/home/username/public_html/nitin2/media/') / "Downloads/nitin").replace('\\','/') if not os.path.isdir(f"{downloads_path}/{str(row['Applicant Name'])}"): os.makedirs(f"{downloads_path}/{str(row['Applicant Name'])}") pdf.output(f"{downloads_path}/{str(row['Applicant Name'])}/document.pdf", 'I') #pdf.output(f'document.pdf', 'D') template=lot.template_type f = open(f"/home/username/public_html/nitin2/media/{template.template_file}", "r") txt=(f.read()) k=k+1 n=n+1 return JsonResponse({'context': "done"}) I want now to show download dialogue box. Currently if … -
Need help about redirecting views in Django
I a beginner in learning Django and have met with an issue that need everyone help. I'm working on a web application for reading novels. I met with an issue that is related to views redirecting in Django. It's about how I can open the chapter page that I clicked on and read it perfectly normal but when I want to return to the novel index page by clicking on the link, I'm met with a NoReverseMatch error. I'll post my code below: This is what I configured in the urls.py: Then I created and configured the urls.py like this: And this is my views.py: The part that I've met with issue is an Html page for viewing chapter: What I have in mind is that by clicking on the url, I'll be redirected to the novel index page. But what happened is that I'm met with the NoReveseMatch error because the part that should have the slug that point to the index page is blank so I can't redirect to it. Anyone have an idea of what I did wrong ? Any helps or suggestions are appreciated -
How can I filter tags with django-taggit
I'm doing the following to filter the posts by tag. But the problem is when clicking the tag button, I do not see any results. urls.py : urlpatterns =[ ...... path('challengePage/', views.ChallengePage, name ='challengePage'), path('tag/<tag>', views.tag, name='tag_argument'), ] the views.py : def ChallengePage(request): challenges = Challenge_code.objects.prefetch_related('tags').all().order_by('-created_at') tags = Tag.objects.all() context = { 'challenges' : challenges, 'tags':tags, } return render(request,'challengePage.html',context) def tag(request,tag): challenges_tag = Challenge_code.objects.filter(tags__name__in=tag) return render(request, 'tag.html',{'tag':tag, 'challenges':challenges_tag}) the challengePage.html : <div style="text-align: center;"> {% for tag in tags %} <a href="{% url 'tag_argument' tag %}"><button style="text-align: center;" dir="ltr" class="buttonTag buttonTag2" > {{tag.name}}</button></a> {% endfor %} </div> the tag.html : <div class="code_body"> <div class="container_code"> {% for challenge in challenges_tag %} <div class="Box_code"> <p class="title_code"><bdi style=" color: #000;"> {{challenge.title}} <br> {% for tag in challenge.tags.all %} <small>{{tag}}, </small> {% endfor %} </bdi> </p> <a href="{% url 'challenge' challenge.id %}"><button class="button1" style="vertical-align:middle"><span>Join</span></button></a> <p class="name-user"> <bdi> By: {{challenge.auther.username}} </bdi> </p> </div> {% endfor %} -
Django Handling Multiple Image Uploads
I have a simple project that has two different models. One that handles a report and one that stores the images for each report connected by a ForeignKey: class Report(models.Model): report_location = models.ForeignKey(Locations, on_delete=models.CASCADE) timesheet = models.ImageField(upload_to='report_images', default='default.png') text = models.CharField(max_length=999) report_date = models.DateField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.report_location, self.report_date, self.created_by}" class TimeSheetAndPics(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE) report_images = models.ImageField(upload_to='report_images', default='default.png') date = models.DateField(auto_now=True) def __str__(self): return f"{self.report} on {self.date}" My Goal is to have a user fill out the report and then upload multiple pictures, however i cannot figure out how to handle multiple image uploads. I have two forms for each model: class ReportCreationForm(ModelForm): class Meta: model = Report fields = [ 'report_location', 'text', ] class TimeSheetAndPicForm(ModelForm): report_images = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True})) time_sheets = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True})) class Meta: model = TimeSheetAndPics fields = [ 'time_sheets', 'report_images', ] And this is how i try to handle my views: class NewReport(LoginRequiredMixin, View): def get(self, request): context = { 'create_form': ReportCreationForm(), 'image_form': TimeSheetAndPicForm(), } return render(request, 'rakan/report_form.html', context) def post(self, request): post = request.POST data = request.FILES or None create_form = ReportCreationForm(post) image_form = TimeSheetAndPicForm(post, data) if create_form.is_valid() and image_form.is_valid(): clean_form = create_form.save(commit=False) clean_form.created_by = request.user clean_form.save() clean_image_form = … -
Django pass value to subquery inside annotate in a query set with mptt
i have a class based on ListCreateAPIView where i'm modifing get_queryset method.. i need pass inside a subquery for an annotate a paramether but seem OutherRef dosen't work i'm using Mptt library .... subqueryItem works fine, subqueryNested instead says cannot use OuterRef can be used only inside a subquery def get_queryset(self): queryset = super().get_queryset() subqueryItem = Subquery(Item.objects.filter(category=OuterRef('id')).order_by() .values('category').annotate(count=Count('pk')) .values('count'), output_field=IntegerField()) subqueryNested = Subquery(Item.objects.filter(category__in=ItemCategory.objects.get(pk=OuterRef('id')).get_descendants(include_self=True)).order_by() .values('category').annotate(count=Count('pk')) .values('count'), output_field=IntegerField()) queryset = queryset.annotate( collcount = Coalesce(subqueryItem, 0), collcountdeep = Coalesce(subqueryNested, 0), ) -
ModuleNotFoundError: No module named "tip_administration_app"
I'm trying to set up a complete environment to run a Django application on ubuntu 22.04 with gunicorn and nginx. I use a droplet provided by Digital Ocean and i'm trying to follow this tutorial : https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 Everything is going well until I have to link gunicorn to my wsgi.py file. When i'm trying this command : gunicorn --bind 0.0.0.0:8000 tip_administration_app.wsgi I have this error : [2022-12-20 14:08:25 +0000] [20676] [INFO] Starting gunicorn 20.1.0 [2022-12-20 14:08:25 +0000] [20676] [INFO] Listening at: http://0.0.0.0:8000 (20676) [2022-12-20 14:08:25 +0000] [20676] [INFO] Using worker: sync [2022-12-20 14:08:25 +0000] [20677] [INFO] Booting worker with pid: 20677 [2022-12-20 14:08:25 +0000] [20677] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line … -
How to show GenericRelation object field value in list_display?
models.py class ModelA(models.Model): name = models.CharField(max_length=40) class ModelB(models.Model): name = models.CharField(max_length=100) model_c = GenericRelation("modelc") class ModelC(models.Model): model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, limit_choices_to={"model__in":["modelb", "modelx", "modely"]}, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() details = GenericForeignKey("content_type","object_id") admin.py class AdminModelB(admin.ModelAdmin): list_display = ("name", "model_a") @staticmethod def model_a(obj): return obj.model_c.model_a # 'GenericRelatedObjectManager' object has no attribute 'model_a' I have ModelB having GenericRelation in field model_c where ModelC contain ContentType as ForeignKey. Now I want to display ModelA.name in list_display of ModelB. I have tried like other foreignkey fields but it gives me an error 'GenericRelatedObjectManager' object has no attribute 'model_a'. -
How to connect my HTML file with CSS file inside of a Django Project
I have a simple html page that works and renders properly on my local browser, but when I reference the static css file the page loads without the styling and I get a 200 Success for the url but 404 for the style.css file I used <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> inside of the HTML file. I have the static folder in the correct spot at the project level and then a css file inside that followed by the style.css file. The Html page: {% load static %} <!DOCTYPE html> <html> <head> <title>My Website</title> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> </head> <body> <h1>Home</h1> <header> <nav> <ul> <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'about' %}">About</a></li> <li><a href="{% url 'info' %}">Info</a></li> </ul> </nav> </header> </body> </html> The CSS page: h1 { background-color: orange; } From the research I've done this should get the backgrounds of all the h1 tags orange but it is not working. Any Advice? -
I have a problem with django-taggit persian[farsi-fa]
I have a problem when I put persian tags in the Django admin panel I get this error in template: Reverse for 'post_tag' with arguments '('',)' not found. 1 pattern(s) tried: ['tags/(?P<tag_slug>[-a-zA-Z0-9_]+)/\\Z'] Note: when I put English and other languages tag I don't get this error and it works True. models.py from django.db import model from taggit.managers import TaggableManager class Article(models.Model): ... tags = TaggableManager() views.py from django.views.generic import ListView class ArticleTagList(ListView): model = Article template_name = 'blog/list.html' def get_queryset(self): return Article.objects.filter(tag__slug=self.kwargs.get('tag_slug')) urls.py from django.url import path from .views import ArticleTagList app_name = 'blog' urlpatterns = [ ... path("tags/<slug:tag_slug>/", ArticleTagList.as_view(), name='post_tag'), ... ] blog/list.html ... {% for tag in article.tags.all %} <a href="{% url 'blog:post_tag' tag.slug %}">{{ tag.name }}</a> {% endfor %} ... enter image description here I change django-taggit version to last version bun not working. I'm now using 3.1.0 version. What can I do? Is there any solution for this problem? -
How to make a dropdown unclickable until a value from another dropdown is chosen, and use that value to filter the dropdown in Excel and Pandas
So I have an excel file that I generated with pandas that has a sheet with two columns A and B that are dropdowns (The values of those dropdowns are coming from another sheet in the same excel file), I want B to be unclickable for any row until A has been filled for any row. And after that, I want the value in A to be used to filter the dropdown in B. Does anyone have an idea how to go about it? This help will be greatly appreciated -
Django - Get all Columns from Both tables
models.py from django.db import models class DepartmentModel(models.Model): DeptID = models.AutoField(primary_key=True) DeptName = models.CharField(max_length=100) def __str__(self): return self.DeptName class Meta: verbose_name = 'Department Table' class EmployeeModel(models.Model): Level_Types = ( ('A', 'a'), ('B', 'b'), ('C', 'c'), ) EmpID = models.AutoField(primary_key=True) EmpName = models.CharField(max_length=100) Email = models.CharField(max_length=100,null=True) EmpLevel = models.CharField(max_length=20, default="A", choices=Level_Types) EmpPosition = models.ForeignKey(DepartmentModel, null=True, on_delete=models.SET_NULL) class Meta: verbose_name = 'EmployeeTable' # Easy readable tablename - verbose_name def __str__(self): return self.EmpName This is my models.py file I have 2 tables and want to join both of them. also want all columns from both tables. emp_obj = EmployeeModel.objects.select_related('EmpPosition'). \ only('EmpID', 'EmpName', 'Email','EmpLevel', 'DeptName') I have tried to do this but there is an error saying EmployeeModel has no field named 'DeptName' How can I get all these columns? -
Get value of a variable inside a function inside a class from another file
i'm trying to fetch the value of a variable inside a function inside a class from another file. this is the class in another folder app/views class ReportVisualisations(TemplateView): def clean(self): xyz = 10 print(app.views.ReportVisualisations.clean.xyz) getting the error 'function' object has no attribute 'xyz' and when i'm trying to print link print(stitch.views.ReportVisualisations().clean().xyz) I'm getting the following error 'NoneType' object has no attribute 'xyz' please help me out on this I'm able to print it if it's inside the class but outside the function using print(app.views.ReportVisualisations.xyz) -
django Test discovery Issues
i run ./manage.py test and i got this err ... test_create_default_action_with_deadline (masoon.anomalies.tests.anomaly.AnomalyCreateDefaultAction) ... ok masoon.actions.admin (unittest.loader._FailedTest) ... ERROR masoon.actions.models (unittest.loader._FailedTest) ... ERROR masoon.anomalies.models (unittest.loader._FailedTest) ... ERROR ... ====================================================================== ERROR: masoon.actions.admin (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: masoon.actions.admin Traceback (most recent call last): File "/usr/lib/python3.10/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/usr/lib/python3.10/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/home/vahid/project/py/django/masoon/actions/admin/__init__.py", line 1, in <module> from .actions import ActionsAdmin File "/home/vahid/project/py/django/masoon/actions/admin/actions.py", line 8, in <module> class ActionsAdmin(AbstractBaseAdmin): File "/home/vahid/project/py/django/masoon/.venv/lib/python3.10/site-packages/django/contrib/admin/decorators.py", line 100, in _model_admin_wrapper admin_site.register(models, admin_class=admin_class) File "/home/vahid/project/py/django/masoon/.venv/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 126, in register raise AlreadyRegistered(msg) django.contrib.admin.sites.AlreadyRegistered: The model Action is already registered with 'actions.ActionsAdmin'. filetree: ... ├── actions │ ├── admin │ │ ├── action_report.py │ │ ├── actions.py │ │ ├── answer.py │ │ ├── __init__.py │ ├── api ... │ ├── apps.py │ ├── __init__.py │ ├── models │ │ ├── action.py │ │ ├── action_report.py │ │ ├── answer.py │ │ ├── __init__.py ├── infrastructure │ ├── asgi.py │ │ ... │ ├── urls.py │ └── wsgi.py ├──settings ... │ ├── apps.py │ ├── files.py │ ├── __init__.py │ ├── logging.py │ ├── main.py │ ├── middlewares.py ... ├── manage.py ... but when i run ./manage.py test modulname.tests … -
condition in dict not push correctely
i have 2 type of questions in quiz plateforme, one choice with radiobutton and multichoice with checkbox, when the checkbox is in begin of quiz it's work , if it's in second question or in the last i have an error , and in my consol log the rep in not an array in my html i have data who contain questions ans reps and type of reps: <div class="repsCol"> {% for Question_reponse in Questions_reponses %} <div class = "Question {% if forloop.first %}active{% endif %}"> <div class = "title_section_quiz"> <h2 class="qst">{{Question_reponse.question}}</h2> <div class = "Reponses"> <div class = "img_quiz"> <img src="{% static 'img/sbg1.png' %}" width="300" height="300" alt=""> </div> <div class = "reps_quiz"> {% for rep in Question_reponse.reps %} {% if Question_reponse.question_type == 'normal' %} <label class="container_radio" ><input type="radio" id = "chSub" class="subRep" name = "rep" value="{{rep}}">{{rep}}<span class="checkmark_radio"></span></label> {% elif Question_reponse.question_type == 'multiples' %} <label ><input type="checkbox" id = "chSub" class="subRep" name = "repCheck" value="{{rep}}">{{rep}}</label> {% endif %} {% endfor %} </div> </div> </div> </div> {% endfor %} <div class = "ButtonNext containerButNxt"> <input id = "ButNxt" type="button" onclick="Next()" value = "Question suivate"> </div> </div> and the function next() in jquery : const allData = []; function Next(){ //console.log(document.getElementsByClassName('Question active')[0].getElementsByTagName('p')[0].innerText); … -
Django - missing 1 required positional argument: 'category_slug'
i keep getting this error in every view of my Django project: categoryFilter() missing 1 required positional argument: 'category_slug'. website is my app name. I don't know why I keep getting this error and I'm new in Django, so your helps make me happy. Here is my django views.py, urls.py, models.py and settings.py files, My views.py: from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Service, Category # Create your views here. def home(request): return render(request, "website/home.html") def services(request): return render(request, "website/services.html") def allCategories(request): return { 'categories': Category.objects.all() } def portfolio(request): service = Service.objects.all() return render(request, "website/portfolio.html", {'services': service}) def serviceDetail(request, slug): service = get_object_or_404(Service, slug = slug, is_active = True) def categoryFilter(request, category_slug): selected = get_object_or_404(Category, slug = category_slug) service = Service.objects.filter(category = selected) return render(request, 'website/portfolio-category.html', {'category': selected, 'service': service}) My urls.py: from django.urls import path from . import views # app_name = 'website' urlpatterns = [ path('', views.home, name = 'home'), path('index', views.home), path('services', views.services, name = 'services'), path('portfolio', views.portfolio, name = 'portfolio'), path('our-story', views.our_story, name = 'our_story'), path('contact-us', views.contact_us, name = 'contact_us'), path('login', views.login, name = 'login'), path('register', views.register, name = 'register'), path('profile', views.profile, name = 'profile'), path('cart', views.cart, name = 'cart'), path('search/<slug:category_slug>/', views.categoryFilter, …