Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Celery IntegrityError
I want to create a progress bar for my project. I have a class and this class has some functions. Especially, one of them takes a long time (def download_all) and this is my main reason for wanting to create a progress bar. I successfully set up celery, celery-progress, etc. and they work all fine. My problem is this: I want to integrate the progress bar to download_all function. I It gives an error: IntegrityError at /o.../k... NOT NULL constraint failed: django_celery_results_taskresult.task_id How can I solve it? functions.py class myClass(): def __init__(self, n_user, n_password, n_url, n_port, db_password, username): ... self.download_all(n_user, n_password, n_url, n_port, db_password) ... @shared_task(bind=True, name="my_add") def download_all(n_user, n_password, n_url, n_port, db_password) ... len_scans = len(scans) progress_recorder = ProgressRecorder(self) for s in scans: i = 0 progress_recorder.set_progress(i + 1, len_scans) i += 1 views.py def setup_wizard(request): ... functions.Zafiyet(setup.n_username, setup.n_password, setup.n_url, setup.n_port, setup.db_password, username=request.user.username) traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/operasyonmerkezi/konfigurasyon Django Version: 3.2.7 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard', 'accounts', 'logs', 'crispy_forms', 'django_apscheduler', 'easy_timezones', 'django_celery_results', 'celery_progress'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\edeni\Desktop\hawkdragon\myvenv\lib\site-packages\django\db\models\query.py", line 581, in get_or_create return self.get(**kwargs), False File "C:\Users\edeni\Desktop\hawkdragon\myvenv\lib\site-packages\django\db\models\query.py", line … -
Error zincrby() got multiple values for argument 'amount'
r.zincrby(name=self.get_product_key(product_id), amount=1, value=with_id) The func where the error occurs. I dont know why amoun get multiple values if I pass all arguments by their names. Code of func zincrby: def zincrby(self, name, amount, value): "Increment the score of ``value`` in sorted set ``name`` by ``amount``" return self.execute_command('ZINCRBY', name, amount, value) Func get_product_key return string Code from the book Django 2 in exapmles: def products_bought(self, products): product_ids = [p.id for p in products] for product_id in product_ids: for with_id in product_ids: # Take products bought with this if product_id != with_id: # Increase their rating r.zincrby(self.get_product_key(product_id),with_id,amount=1) If not difficult, you can explain what each zincrby function argument is responsible for.I understand that after performing this function, I will have a rating for each product with the most frequently purchased products with this product. The code itself is from the recommendation service. -
Pass request.user parameter to modelformset_factory form
So I've a formset tied to a model and one of the fields in that is ForeignKey. models.py class Squad(models.Model): rid = models.AutoField(primary_key=True) team = models.ForeignKey(Team, on_delete=models.CASCADE) def __str__(self): return self.team.tname forms.py class SquadForm(ModelForm): class Meta: model = Squad def __init__(self, logged_user, user, *args, **kwargs): super(SquadForm, self).__init__(*args, **kwargs) self.fields['team'] = forms.ModelChoiceField(queryset=Team.rows.get_my_teams(user=logged_user), empty_label="None") As you can see, the __init__ function is expecting an extra parameter logged_user which I'm hoping to pass via the views.py file. But if I do the following: views.py def choose_teams(request): teamformset = modelformset_factory(Squad, extra=2, form=SquadForm(request.user)) form = teamformset(queryset=Squad.objects.none()) return render(request, 'foo.html', {'form':form}) I'm trying to pass the logged in user as a parameter on line 2 but this is resulting in the following message: Field 'id' expected a number but got 'SquadForm' Not sure what I'm missing here. But if I remove the parameter from line 2: teamformset = modelformset_factory(Squad, extra=series.team_number, form=SquadForm) it starts working (of course, I no longer expect the user in the forms.py file and remove it too) but shows all the data and not filtered one. -
Django using PostgreSQL - duplicated indexes
I'm using Django over PostgreSQL, and I'm having trouble understanding how to use indices correctly to achieve the best performance. This is an example Model: class SomeObject(BaseAggModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) element = models.ForeignKey(Element, on_delete=models.PROTECT, db_index=True) city = models.ForeignKey(City, on_delete=models.PROTECT, db_index=True) date_created = models.DateTimeField(null=True) class Meta: unique_together = ('element', 'city', 'date_created') indexes = [ models.Index(fields=['city ', 'element']) ] My questions are regarding how to change the indices to have as few indices as possible but maintain the best performance possible. Since I have the unique_together, and element is the first entity in that index. Does it necessarily mean that I can change the element field to have db_index=False since I already have a combined index to this field? Since I have the index over city and element together, and city is the first entity in this index. Does it necessarily mean I can change the city field to have db_index=False since I probably don't need a dedicated index for it? Alternatively (instead of doing the previous changes mentioned), since I have the unique_together and also the Index. If I will reorder the unique_together to be over (city, element, date_created), will it make the index over (city, element) redundant and … -
Set a limit for forms with the same value Django
So what I want to do is to set a limit of forms with the same value. There are different activities from a foreign model to which students can apply. I have name(naam), student number(studentnummer), activity(activiteit) and class(klas), and I want to set a limit of 10 forms with the same activity (max of people who can do the same activity) and a limit of 1 for student number (so students can only apply for one activity). models.py class Klas(models.Model): klas = models.CharField(max_length=8) def __str__(self): return f"{self.klas}" class Activiteit(models.Model): titel = CharField(max_length=64) docent = CharField(max_length=32) icon = models.ImageField() uitleg = models.TextField() def __str__(self): return f"{self.id}:{self.titel}:{self.docent}" class Aanmelden(models.Model): naam = CharField(max_length=32) studentnummer = IntegerField() klas = ForeignKey(Klas, on_delete=models.CASCADE, default=None, blank=True) activiteit = ForeignKey(Activiteit, on_delete=models.CASCADE, default=None, blank=True) def __str__(self): return f"{self.id}:{self.naam}:{self.studentnummer}" views.py def home(request): activiteiten = Activiteit.objects.all() form = AanmeldenForm() if request.method == 'POST': form = AanmeldenForm(request.POST) if form.is_valid(): form.save() return render(request, 'home.html', { 'activiteiten': activiteiten, 'form':form, }) forms.py class AanmeldenForm(forms.ModelForm): class Meta: model = Aanmelden fields = ( 'naam','studentnummer','klas','activiteit' ) If you know how to solve this or have a better idea of doing this kind of system please let me know. Thanks in advance!! -
User model and User auth (Django and mysql)
I am new to py web dev. I am using django and mysql for my web app. My app works but i am not able to maintain the login session. after each query on main page it redirect me to login page. The reason for that is im not using the django User auth system instead i wrote my own auth code inside ```view.py ``` def login(request): if request.method == "POST": form = Studentlogin(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') try: currstudent = students.objects.get(email=email, password=password) expense = sublist.objects.all() return render (request, 'subscrap/main.html', {'student': currstudent, 'sublist': expense }) except: messages.success(request, 'Error, either Email or Password is not correct') pass else: form = Studentlogin() return render(request, 'subscrap/login.html', {'form': form}) the login data is only accessible inside the login function and I have to call it every time to render and see an updated main.html. I searched on the web and the clue I got was that it might be because my user model aka(class students) is not actually built like a user model. I am a newbie to the py syntax and web dev on it and confused about how to implement Django user auth and save my info in … -
DJANGO Passing markdown into template
I have attempted to pass a markdown text into the html template. I have also disabled autoescaping within the html template but there is still an error when attempting to render the html template page. Could the safe filter not be working? views.py content = util.get_entry(title) if content: return render(request, "encyclopedia/entry_page.html", { "title": title, "entry": markdown.markdown(content) }) else: return render(request, 'encyclopedia/404.html', status=404) entry_page.html {% block title %} {{ title }} {% endblock %} {% block body %} {{ entry|safe }} <br> <a href="{% url 'edit_page' title=entry %}">Click here to edit the page.</a> {% endblock %} -
What is the best topic to research in M Tech for a programming lover [closed]
What is the best topic to research in M Tech for a programming lover. I love to code. Angular, Django, Python etc. I do enjoy coding. But now I am stuck in M tech and I have to do a research, and I am having a very hard time to select the topic. Help! -
How to populate a dropdown from another dropdown's selected value in Django
I have 2 models, one model is of the users and another of videos. user_id is acting as a foreign key for the videos model. I have created 2 dropdowns using the select/option tags. models.py class Users(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Videos(models.Model): user = models.ForeignKey(Users,on_delete=CASCADE) def __str__(self): return self.user.name I have populated the first dropdown by retrieving all the users from the DB and sending them to the template in views.py. What I want is, as soon as I select one of the users in the first dropdown all the videos corresponding to that particular user should appear as options in the second dropdown. <div class="mb-3"> <label class="py-1" for="Select_participant">Select Participant:</label> <select name = "selected_user" class="form-select" required aria-label="select example"> {% for user in users %} <option value="{{user.id}}">{{user.name}}</option> {% endfor %} </select> </div> <div class="mb-3"> <label class="py-1" for="URL">Select Video:</label> <select class="form-select" required aria-label="select example"> <option value="/path">video1</option> </select> </div> I am not able to figure out to achieve this. I was thinking like first sending the value of the selected user to the backend, and then filtering the videos w.r.t that particular user and then again rendering the template, but it will become much complex. Are there any easy … -
Django related objects reference remove(obj, bulk=False)
I've tried to use related manager remove() method with bulk=False but no success.Can anyone tell me what happened and where is mistake ? Thanks. In order to use remove(obj, bulk=False) I created models like Then I tried method itself in interactive shell like bellow: I've created musician object created album object with Foreign key to musician object but I didn't save it I called related manager on musician object to remove album from relation with option bulk=False => I expected that this will call save on my album object and than remove foreign key relation but nothing happened, album wasn't saved nor relation on musician was removed. I expected the final call to album to give me <Album: First album None> and album to be saved in data base but it didn't happen. The same procedure implemented on add(obj, bulk=False) yield expected results add(album2, bulk=False) saved my alabum2 and added reference to musician object -
How to generated HMTL Sitemap in Django
I want to create HTML sitemap in Django like enter image description here -
django-oscar-api conflict with Django's UpdateCacheMiddleware: {TypeError}cannot pickle '_io.BufferedReader' object
I implemented django's per site cache in a django-oscar project with django-oscar-api. I use LocMemCache as a cache backend. Before adding django.middleware.cache.UpdateCacheMiddleware to my middlewares, everything worked fine and I could make a request to the "basket" endpoint like this and it returned a 200 response: import requests session = session.Session() r_basket = session.get("http://127.0.0.1:8000/api/basket/") After adding the per-site caching the response has the status code 500. I debugged it and it fails in the UpdateCacheMiddleware with the following error: {TypeError}cannot pickle '_io.BufferedReader' object. Other endpoints seem to work fine, but I haven't tested them all yet. The error can also be reproduced on a freshly installed django-oscar sandbox. I pip-installed the django-oscar-api and added it to the installed apps, and the MIDDLEWARE setting looks like this: MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', # Allow languages to be selected 'django.middleware.locale.LocaleMiddleware', 'django.middleware.http.ConditionalGetMiddleware', 'django.middleware.common.CommonMiddleware', # per site caching 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', # Ensure a valid basket is added to the request instance for every request 'oscar.apps.basket.middleware.BasketMiddleware', ] My package versions are Django v.3.2.9, django-oscar v.2.2 or 3.0, django-oscar-api v.2.1.1. What object can not be pickled? Or is the order of the middlewares possibly wrong? -
Foreign Key relationship at second level
Suppose I have three models such as - class company(models.Model): companyName = models.charField() class branch(models.Model): branchName = models.charField() company = models.ForeignKey(company, on_delete=models.CASCADE) Now in the third model, that is customer I want to have unique customer per compnay so I did - class customers(models.Model): customerName = models.charField() branch= models.ForeignKey(branch, on_delete=models.CASCADE) company = models.ForeignKey(company, on_delete=models.CASCADE) class Meta: unique_together = ( ('company', 'customerName'), ) Now since the branch has already got company as a foreign field and I'm again using both branch and company in the customers model, will this form a cyclic structure, or is this a wrong way of doing it? And if I remove the company from the customers model because branch already has company as a foreign field, how can I set unique customers per company at the database level? -
Django Tempus Dominus: setting a format makes the form invalid
I have a very simple form to submit a date. By default, the date format is 'yyyy-MM-dd' and the form works. However as soon as I change format to anything (I tried False and 'LL'), I get an error message on submission: 'Enter a valid date'. So it looks like on submission the default format is used rather than the one I've set. How do I get the preferred format working? Here is the form: class DateForm(forms.Form): date_field = forms.DateField( required=True, label='The Date', widget=DatePicker( options={ 'minDate': '1900-01-01', 'maxDate': '2050-12-31', 'format': 'LL', }, ), initial='2001-01-01', ) And here is the view: def date_input(request): if request.method == 'POST': form = DateForm(request.POST) if form.is_valid(): the_date = form.cleaned_data['date_field'] print(the_date) else: form = DateForm() return render(request, 'calculators/date-input.html', { 'form': form, }) -
How to create a django rest api for django website users
I am new to django rest framework and have basic knowledge of django. I have a note taking app where user can signin add,edit and delete there notes. I want to create an drf api for user so that they can get, post, updated and delete there notes using api. I don't find any tutorial similar to my requirements on internet. Any advice/examples will be appreciated -
Slug field does not work for Bengali language in django. How to work with slug in bengali
Django slug field does not work for any other language except English. I want to work with Bengali language here is the code class Post(models.Model): title = models.CharField(max_length=140) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) content = RichTextField(default="") image = models.ImageField(upload_to="media/post") url = models.SlugField(unique=True, max_length=250, null=True, blank=True) likes = models.IntegerField(default=0) created_date = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.title}" def save(self, *args, **kwargs): # new if not self.url: slug_str = f"{self.title}-{datetime.datetime.now()}" self.url = slugify(slug_str) return super().save(*args, **kwargs) -
How to change path to file in django
I use private storage in django, files are saved in a private path. In django setting the path to the files: PRIVATE_STORAGE_ROOT_FILES = os.path.join(BASE_DIR, 'private/private_files') I declare the file path for the model: ##storage for the private files private_storage_fles = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT_FILES) And in my Model: private_file = models.FileField(blank=True, null=True, storage=private_storage_files) Now i want to copy the project to another computer for testing. However the files are not found on the new computer because the file paths are different on the new computer. Sow on computer 1 the saved instance has the following file path: c:/users/computer1/document/djangoproject/private/file.pdf But on computer 2 this path does not exist. Can i solve this problem? -
How can i print out multiple querried objets via html template
class License(models.Model): agency = models.ForeignKey(Agency, on_delete=models.CASCADE) contact_person = models.ManyToManyField(ContactPerson()) description = models.CharField("License Description", max_length=250) location = models.CharField(max_length=20) renewal_frequency = models.CharField("Renewal Frequency", max_length=20) sop = models.FileField(upload_to="sop") class Timeline(models.Model): license = models.ForeignKey(License, on_delete=models.CASCADE) last_renewed = models.DateField() due_date = models.DateField() lpo = models.FileField(upload_to="lpo") comment = models.TextField("Comment", max_length=250, null=True, blank=True) report = models.FileField(upload_to="reports", null=True,blank=True) def home(request): title = "Licences" agencies = Agency.objects.all() agent =Agency.objects.get(pk=1) licenses = License.objects.all() for license.id in licenses: timeline = Timeline.objects.select_related().filter(license_id = license.id).order_by('-id')[:1] print(timeline) {% for renewal in timeline %} <tr> <td align="center"> <a href="{% url 'licenseupdate' renewal.license.id %}" class="btn btn-default"><em class="fa fa-pencil"></em></a> <a href="{% url 'removeobject' renewal.license.id %}" class="btn btn-danger"><em class="fa fa-trash"></em></a> </td> <td> <a href="{% url 'timelines' renewal.license.id %}"> {{renewal.license.description}}</a></td> <td>{{renewal.license.location}}</td> <td>{{renewal.license.renewal_frequency}}</td> <td>{{renewal.last_renewed}}</td> <td>{{renewal.due_date}}</td> i am trying to pring out all my License models with the latest timeline related to it, but the for loop only returns one license. only one license gets displayed to my template. -
Django Reverse One-To-One relationship
I am trying to access via One-to-One reverse relationship characteristics in my django project. my models.py: class MyCustomUser(AbstractUser): username = models.CharField(max_length=50, unique="True", blank=False, primary_key=True) password = models.CharField(max_length=200, blank=False) class Researcher(models.Model): user = models.OneToOneField(MyCustomUser, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=True) email = models.EmailField(blank=True, unique="True") in my views.py: def loginView(request): if request.method == "POST": user = authenticate(username=request.POST['username'], password=request.POST['password']) print(user.researcher.name) if user is not None: login(request, user) if user.isResearcher == True: return redirect('diagnosis:index') elif user.is_superuser == True: return redirect('diagnosis:index') return redirect('diagnosis:index') in my template: <div class="fw-bolder d-flex align-items-center fs-5">{{ user.researcher.name }} <p class="fw-bold text-muted text-hover-primary fs-7">{{ user.researcher.email }}</p> Now it shows an error with the line(views.py): print(user.researcher.name) Also, with {{ user.researcher.email }} I can't get reverse access of email field in my template. Please suggest me how can I fix this? -
Django UNIQUE constraint failed when using signals
UNIQUE constraint failed: brand_brand.slug. class Brand(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) log = models.ImageField(upload_to='brands') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.name = self.name.lower() return super(Brand, self).save(*args, **kwargs) @receiver(pre_save, sender=Brand) def create_brand_slug(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(instance.name) class BrandForm(ModelForm): class Meta: model = Brand fields = ['name', 'log'] I am saving the brand name in small letters in the database. When am tried to save the existing brand name in the capital letter, I Got UNIQUE constraint failed: brand_brand.slug error. When tried to save the exiting brand name with all in small letters, I got the proper error 'Brand with this Name already exists.' -
Hello, I cannt write Georgian shrift, when I generate pdf , using django . My code writes black squares besides georgian letters
I generate pdf files about each models object, but in pdf, i cannt write with Georgian letters, it returns black squares. here is some code, i am using : from xhtml2pdf import pisa in my urls.py :path('pdf/', views.customer_render_pdf_view, name='costumer-pdf-view') def customer_render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') customer = get_object_or_404(id, pk=pk) template_path = 'test.html' context = {'customer': customer} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename= "report.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response, encoding='utf-8' ) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response -
Django Inline Formset Clean method not raising validation error in template?
i am using inline formset and i have use clean method but clean method not raising error and i used '{{ formset.non_form_errors }}' also. below clean method snipped print statement reaching last moment till reaching after not raising validation error. why ? if self.instance.tax not in (None, ''): if total != self.instance.tax: self.errors.append({"error":"The Sum of different Tax Breakups should be equal to total TAX rate"}) print("reaching last moment") raise forms.ValidationError("The Sum of different Tax Breakups should be equal to total TAX rate") -
ModuleNotFoundError: No module named 'brandscrispy_forms'
my crispy form is not working showing, ModuleNotFoundError: No module named 'brandscrispy_forms'. I think brandcrispy is the inner package of crispy forms -
No module named 'keyboard' in Pythonanywhere
I successfully installed the keyboard module with pip install keyboard. But when I run the code it says No module named 'keyboard'. All other modules run successfully after installing. I don't know what I am missing here. Any help would be appreciated. -
DJANGO: Set site_id to sites pk
I am following this tutorial for email verification.The version the author is working with is old.I got an error that said Reverse for ‘activate’ with keyword arguments ‘{‘uidb64’: b’OA’, ‘token’: ‘4tm-3fcfb375c8ba14f9a95b’} . I got that fixed through the first comment . The email got sent .But the link led to www.example.com . The second comment tells how to fix that . The comment was : For those are using Django 3, You should change some code Six is deprecated in Django 3, you can use ‘import six’ instead of ‘from django.utils import six’ To send html email, add email.content_subtype = “html” after EmailMessage Object. activate url should be path(‘activate//’, views.activate, name=’activate’), get_current_site(request) will return example.com as default when SITE_ID=1 in your settings.py. Add your site name and domail in admin site (/admin/sites/site/) and replace SITE_ID with your sites pk. But I did not understand how to set SITE_ID to my sites pk.