Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: dropdown is populated with the id of a ForeignKey, but i would like to populate it with its textual value (and not the id)
In the dropdown I get the campionato id, because I'm selecting a ForeignKey. I would like to populate the dropdown with the textual value of the sampled ForeignKey and not with the id. IMPORTANT: Considering that the two dropdowns are dependent, I had to use campionato of the Full_Record class (and not the one of the Campionato class) I have read several solutions and similar questions, but they didn't help me. Here is my code models.py from django.db import models from smart_selects.db_fields import ChainedForeignKey from django.contrib import admin #### BASIC DATA #### #Campionato class Campionato(models.Model): stagione = models.ForeignKey(Stagione, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name #Teams class Teams(models.Model): stagione = models.ForeignKey(Stagione, on_delete=models.CASCADE) campionato = models.ForeignKey(Campionato, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name #### FULL RECORD #### class Full_Record(models.Model): campionato = models.ForeignKey(Campionato, on_delete=models.CASCADE) team_home = ChainedForeignKey( Teams, related_name='team_home_name', chained_field="campionato", chained_model_field="campionato", show_all=False, auto_choose=True, sort=True) team_away = ChainedForeignKey( Teams, related_name='team_away_name', chained_field="campionato", chained_model_field="campionato", show_all=False, auto_choose=True, sort=True) def partita(self): return f"{self.team_home}-{self.team_away}" def __str__(self): return self.campionato forms.py {% extends 'base.html' %} {% block content %} <!-- First Combobox --> <label for="id_campionato">Country</label> <select name="campionato" id="id_campionato" hx-get="{% url 'trips' %}" hx-swap="outerHTML" hx-target="#id_trip" hx-indicator=".htmx-indicator" hx-trigger="change"> <option value="">Please select</option> {% for campionato in campionati %} <option value="{{ campionato … -
Visual stuido code doesnt run the django site
I started learn django and choose Visual studio code. When i start the site by "python manage.py runserver" it doesnt start, but in Command Prompt it is work. How do improve that?enter image description hereenter image description here I dont know how to improve that -
How to pass a parent id (via foreignkey) if the child form is located on the same template as the parent form?
I am learning Django and I am trying to write a "reply" code for a comment. Currently, when a user clicks the button "reply", the link takes them to a new page, which allows me to pass the parent comment_id to the reply as a foreign key. How can I place the "reply" form on the same page as the comment? I apologize if my question is entirely stupid, I am just learning! Thank you! My current code for the "reply" is: --> how can I pass the comment_id to the reply if the reply form is on the same page as the "comment"? def reply(request, comment_id): comment = get_object_or_404(Comment, id=comment_id) form_reply = ReplyForm(request.POST or None) if request.method == "POST": if form_reply.is_valid(): a_comment = form_reply.save(commit=False) a_comment.comment = comment a_comment.save() return redirect('two_forms') all_replies = Reply.reply_objects.all() return render(request, 'reply.html', {'form_reply': form_reply, 'all_replies': all_replies, }) I tried to place this code on the same template as the "comment" but then the comment_id messes with the url of the comment page and gives an error. -
Trying to update user email using Djoser set_username
I am trying to update my user's username. For some reason when I call /users/set_username it says that: {"current_password":["This field is required."],"new_email":["This field is required."]} So I edited my code to follow that. export const updateUserEmail = (email, password) => dispatch => { const data = { "new_email" : email, "current_password" : password } axios.post("/api/v1/users/set_username/", data) .then(response => { const user = localStorage.getItem('user') let username = JSON.parse(user).username const newUser = { "username": username, "email":email } localStorage.setItem("user", JSON.stringify(newUser)); dispatch({ type: SET_CURRENT_USER, // auth store payload: user }); // dispatch(push("/")); toast.success("Update Successful."); }).catch(error => { // show error toast console.log(error) toastOnError(error); }) } But every time I run this I get a 500 internal server error, but I'm not sure why. I have tried removing the last slash, but that didn't work. I am expecting to update the user's email. -
How to pass an additional parameter to a field on a model that is pointed to by a foreign key in Django?
class File(Model): file = models.FileField('file', validators=[FileExtensionValidator(GET_ALLOWED_EXTENSIONS)]) some_other_fields class User(model): avatar = models.ForeignKey(File, models.PROTECT, '+', allow_extensions=['png', 'jpg']) I want pass allow_extensions through User's avatar field. And file field in File model can get allow_extensions. How do I implement this feature? -
Race condition in Django save()
I have an API that can take a list of files and save it in the DB for a specific user. I want to limit the number of files per user to be some number. The way I enforce this is through overriding the save method: A pseudocode: In the view: For item in list_to_save: item.save() And save method: curr_count= Files.objects.filter(id=user_id).count If curr_count > max_count: Get curr_count-max_count item For del in delete: del.delete() Question is, will this lead to a race condition if the same user tries to send 2 different list of files? Since there might be 2 save operation running at the same time? I am expecting that there is some race condition since the two server will see that DB has entries, and will try to delete them both, leading to some inconsitencies -
django: Recursive function called in views.py method not returning results
I am new to django and web development, I am trying to call a recursive function in views.py on clicking submit button on my form. When I try to call the same function while it returns a simple list, it works fine, but it returns nothing if the core logic is enabled. I am really not sure what's the problem, can anyone tell what's wrong and how to fix it? Following is the implementation of views.py and recursive function: def process_form(request): if request.method == 'POST': print("Request is POST") form = UIForm(request.POST, request.FILES) if form.is_valid(): print("Form is valid") # Create an instance of the model and assign the form data to its fields form_data = FormData() form_data.from_timestamp = form.cleaned_data['from_timestamp'] form_data.to_timestamp = form.cleaned_data['to_timestamp'] form_data.free_text = form.cleaned_data['free_text'] form_data.uploaded_file = form.cleaned_data['file'] # Save the form data to the database form_data.save() file = request.FILES['file'] todayDate = datetime.datetime.now().strftime("%Y-%m-%d") dest_dir = temp_directory + os.sep + todayDate dest_path = dest_dir + os.sep + file.name os.makedirs(dest_dir, exist_ok=True) print("Dest path:", dest_path) # Handle the uploaded file if file: # Save the file to the server's temporary directory with open(f'{dest_path}', 'wb') as destination: for chunk in file.chunks(): destination.write(chunk) # Check the given regular expression against the extracted files pattern = form_data.free_text … -
Make my web page offer download of zipfile
I am building an archive where people can download zip-files (the url is localhost:8000/downloads). I have the zip-files in the games folder (in relation to where manage.py resides). When I pass over with cursor the address shows "localhost:8000/downloads/.../games/GC_007 Goldeneye.zip" which gives "no download" This is what I put in the link: <a href="games/GC_007 Goldeneye.zip" download>007 Goldeneye</a> "localhost:8000/downloads/.../games/GC_007 Goldeneye.zip" is what I get which does not work. -
Like icon and Likes counter does not refresh automatically
I am trying to get a Web page that updates the Likes counter when a user clicks on the Likes icon (similar to Twitter, now X): I am using JavaScript and Django (I am a newbie in both). I am facing this issue: when I click on Like icon ("thumbs up" by default) the Like counter increase but the Like icon does not change to a "thumbs down" icon and indeed if I click on Like icon again then the Like counter increase again. Once I refresh the page manually the Like icon appears as thumb down. I would like that: when I click on Like icon ("thumbs up" by default) the Like counter increase and the Like icon changes to a "thumbs down" icon when I click again on Like icon (it is a "thumb down" icon now) then the Like counter decrease and the Like icon changes to a "thumbs up" icon the above should be gotten without requiring a reload of the entire page (I have to refresh the page manually right now) Please find below my code: index.html {% extends "network/layout.html" %} {% block body %} <!-- Javascript code --> <script> function getCookie(name) { const value … -
Error with static CSS files while deploying django app to Heroku
I'm a new developer here, and I am trying to deploy my first web app (created using Django) and I am using Heroku. I have been getting errors with my static files and while trying to troubleshoot that I've created a few other errors and I am hitting a wall with troubleshooting the errors. Can anyone take a look at the Heroku build log and VSCode and tell me if they see anything? I am trying to deploy my web app using Heroku. My website works fine locally but won't finish deploying. Im getting errors in the static files. I think it might have something to do with the static path. KeyError: 'collectstatic' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/build_0ef1ffd4/manage.py", line 22, in <module> main() File "/tmp/build_0ef1ffd4/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/django/core/management/__init__.py", line 262, in fetch_command settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.11/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.11/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/django/conf/__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) … -
HTTP/1.1" 405 0 Django - Unable to go past Login Page
I created a login page and I have users with 3 roles, Administrator, Student, Supervisor. Each of these users have their separate dashboards. When I login using the username and password, it should check the user's group and based on which should redirect the user to their respective dashboard. When I hit the submit button to login, it gives me an error `. HTTP/1.1" 405 0 Request URL: http://127.0.0.1:8000/ Request Method: POST Status Code: 405 Method Not Allowed Remote Address: 127\.0.0.1:8000 Referrer Policy: strict-origin-when-cross-origin Allow: GET, HEAD, OPTIONS Connection: close Content-Type: text/html; charset=utf-8 Date: Thu, 17 Aug 2023 23:48:51 GMT Server: WSGIServer/0.2 CPython/3.11.3 ` The unfortunate part is that the home page allows only GET requests. Not sure how to change this. I manually forced my app to use post requests by defining them in views.py and forced post request on the form in the home.html file which I use to load my login page. So if you can review the code and help me get past this, it would be of great help. The name of my project is webappsretake2023 and the name of the app is spmsapp spmsapp/views.py from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from … -
EmailAddress model in Django allauth?
I just started using Django allauth, and I noticed that it created a new accounts_emailaddresses table. I understand this is useful for email confirmation, but if feels like this is a source of denormalization in our database. Our current User model already has an email field. It seems like now I have to maintain the state of both User and allauth.EmailAddress models now. For example, when a user changes emails, I need to change the User model and also mark the new email as primary in EmailAddress This seems really annoying...what is the best practice in this case? Should I remove email field from User? I'm wondering how most people handle this. -
Django 'python manage.py runserver' has stopped working. How can I fix this?
I'm attempting to use Django to create a website builder. I have created a development webserver with "python manage.py runserver" and it worked initially. I created a Products app and added code in the views module and the url module under this app, whilst also mapping it to the parent url module using "path('products/', include('products.urls'))" but when I go back to the link produced by the server, it no longer works. I don't know what the problem is and how to fix it, as I didn't do anything different from the first time I tried this, and it worked briefly, before it stopped. I had to start a new project when this happened but I don't have time to keep starting over. This worked a few days ago but the next day the runserver command wasn't working. I had to delete the project and start again and now I am running into the same problem and I don't know what to do -
Django Related Model Calculations
I am creating a dashboard of sorts, I have two related models. Models: class Batch(models.Model): ... batchid = models.AutoField(primary_key=True, serialize=False, auto_created=True) batchsku = models.CharField(max_length=96) productionarea = models.CharField(max_length=96, choices=prod_area_choices, default=PRESS, verbose_name="Production Area") batchlbs = models.DecimalField(max_digits=15, decimal_places=3, blank=True, null=True, verbose_name="Lbs/Batch") batchcases = models.DecimalField(max_digits=15, decimal_places=4, blank=True, null=True, verbose_name="Cases/Batch") def __str__(self): return self.batchsku class BatchProduced(models.Model): ... batchprodid = models.AutoField(primary_key=True, serialize=False, auto_created=True) sku = models.ForeignKey(Batch, related_name="batch_exists", on_delete=models.PROTECT) location = models.CharField(max_length=96, choices=batch_prod_area_choices, default=PRESS1) created_by = models.ForeignKey(User, on_delete=models.PROTECT) created_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.sku For the view I would like to see some specific filtered information from the above models. Specifically I would like to have a count, which I get as part of my view through: pr1batchcount = BatchProduced.objects.filter(created_time__date=today, location='pr1').count() In the same view I would like to be able to calculate pr1batchcount * Batch.batchcases but I am struggling to figure out the best approach. I thought about a model calculation under the BatchProduced model like def expcases(self): return sum([Batch.batchcases for Batch in self.item_set.all()]) But this is failing to return anything, and I am not quite sure I am even pointing the right way. I am not confident in my Django knowledge to know if this is the right approach, I've gone through all related … -
How can I set a "safe" running "mode" that determines the collective behavior of django model superclasses I created?
Sorry for the poorly worded title. I just don't know how to phrase it succinctly, but I think I can best ask my question by example. Here is the background: I have a working Django model superclass I wrote called MaintainedModel. It provides a way to auto-update selected fields in a model class using decorated methods that the developer implements in the derived model class. The execution of those methods is controlled automatically via various overrides in my MaintainedModel superclass, such as an override of the Model.save() method. If a model object ever changes, the "maintained fields" in the derived model are auto-updated. It also provides a means to trigger those updates via changes to related model objects such that updates propagate via a relationship chain. One problem I had to overcome is that the autoupdate methods can sometimes be complex and take some time, especially if there are multiple triggers of the same model object due to multiple triggering related model changes. In the wild, that extra time is not noticeable and you don't encounter this repeated trigger case, but during a load of a mass quantity of data, it can double or triple the load time. I worked … -
Error with sending sms in email with celery
class UserRegistrationForm(UserCreationForm): first_name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-2', 'placeholder': 'Enter first_name' })) last_name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-2', 'placeholder': 'Enter last_name' })) username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-2', 'placeholder': 'Enter username' })) email = forms.CharField(widget=forms.EmailInput(attrs={ 'class': 'form-control py-2', 'placeholder': 'Enter gmail' })) password1 = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control py-2', 'placeholder': 'Enter password' })) password2 = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control py-2', 'placeholder': 'Enter password again' })) captcha = CaptchaField() class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2') # Email validation def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError('This email is invalid') if len(email) >= 350: raise forms.ValidationError('Your email is too long') return email def save(self, commit=True): user = super(UserRegistrationForm, self).save(commit=True) # expiration = now() + timedelta(hours=48) # record = EmailVerification.objects.create(code=uuid.uuid4(), user=user, expiration=expiration) # record.send_verification_email() # return user send_email_verification.delay(user.id) return user import uuid from datetime import timedelta from celery import shared_task from django.utils.timezone import now from user_account.models import EmailVerification, User @shared_task def send_email_verification(user_id): user = User.objects.get(id=user_id) expiration = now() + timedelta(hours=48) record = EmailVerification.objects.create(code=uuid.uuid4(), user=user, expiration=expiration) try: record.send_verification_email() except Exception as e: print(f"Failed to send verification email: {e}") I have a problem connecting celery to sending sms to mail in the console it says that I sent sms … -
Why is my Django view not recieving input from my HTML form?
I am making a website that takes user text, modifies it and returns a response using Ajax. I am using Django on the backend and vanilla JS on the frontend. The user chooses source_language and target_language, enters some text in input_text and the browser outputs a translation in the output_text textarea. However whenever I try I keep getting either a None as output_text(as the output from my translation API) or a No Null error for input text whenever it tries to save to the database, so it seems the input text is not being detected by my django view. The same goes for the source language and target language. When I comment out the code to save translation to the database I get None as ouput text. However when I check the payload (in developer tools) being sent I see the input text and the selected languages. I use the <form> tag in my HTML with AJAX so as to prevent page reloads when the user recieves a response. When I remove all JS it works as expected but of course the presenation is a black screen and requires a page reload. Here is my code: JS: const csrfToken = … -
Django field with foreignKey
I'm using Django v4.1 and have a foreignKey relationship I want to pull into a form. The two models: class Service(models.Model): client = models.ForeignKey("Client", on_delete=models.SET_NULL, null=True) # some other fields and class Client(models.Model): name = models.CharField(max_length=50) # a few more fields The form: class ServiceForm(forms.ModelForm): class Meta: model = Service fields = "__all__" However, in the front-facing form, "Client" is generated, but without a SELECT field. There is another model with a foreignKey relationship to Client, order: class Order(models.Model): client = models.ForeignKey("Client", on_delete=models.SET_NULL, null=True) # more fields... And it's form: class OrderModelForm(forms.ModelForm): class Meta: model = Order fields = "__all__" Which renders as expected with a SELECT field for the Client. Looking at the forms docs I experimented with (importing Client from models and) adding a ModelChoiceField, ("client": forms.ModelChoiceField(queryset=Client.objects.all()) both inside and outside of a widgets dict), but based on this SO post I'm thinking Django should be rendering that on it's own, as it is for Order. Please share suggestions in debugging. Thanks much. -
cron django, task launch only by command `python manage.py cron run`
I haven`t big experience with cron so want to ask you about my problem. I have to task for cron 1. def start_scraping(): prompts = Get_search_info() for prompt in prompts: stop = False category = prompt.category.link if prompt.category else "oferty" ignore_clone = prompt.just_created text = prompt.text.replace(" ", "-") link = f"https://www.olx.pl/{category}/q-{text}/" response = requests.get(link).text page_soup = BeautifulSoup(response, "html.parser") page_number = int(page_soup.find_all(attrs={"data-testid": "pagination-list-item"})[-1].text) for page in range(1, page_number + 1): if stop: break pagelink = f"{link}?page={page}" response = requests.get(pagelink).text page_soup = BeautifulSoup(response, "html.parser") cards = page_soup.find_all(attrs={"data-cy": "l-card"}) cards_links = [] for card in cards: card_url = card.find("a").get("href") if card_url not in cards_links and card.find(attrs={"data-testid": "adCard-featured"}) is None: cards_links.append(f"https://www.olx.pl{card_url}") print(card_url) is_exist = Add_new_link(cards_links, prompt.id) if is_exist and not ignore_clone: stop = True if prompt.just_created: change_created_status(prompt) def start_scraping(): prompts = Get_search_info() for prompt in prompts: stop = False category = prompt.category.link if prompt.category else "oferty" ignore_clone = prompt.just_created text = prompt.text.replace(" ", "-") link = f"https://www.olx.pl/{category}/q-{text}/" response = requests.get(link).text page_soup = BeautifulSoup(response, "html.parser") page_number = int(page_soup.find_all(attrs={"data-testid": "pagination-list-item"})[-1].text) for page in range(1, page_number + 1): if stop: break pagelink = f"{link}?page={page}" response = requests.get(pagelink).text page_soup = BeautifulSoup(response, "html.parser") cards = page_soup.find_all(attrs={"data-cy": "l-card"}) cards_links = [] for card in cards: card_url = card.find("a").get("href") if card_url … -
Prefetching related objects for templates
I have two models, Signup and Report, related via a third model, Training: class Signup(models.Model): pilot = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="signups" ) training = models.ForeignKey( Training, on_delete=models.CASCADE, related_name="signups" ) class Report(models.Model): training = models.OneToOneField( "trainings.Training", on_delete=models.CASCADE, primary_key=True ) And e.g. in the update view for a Report I try to prefetch the Signups and their Pilots and sort them into the context: class ReportUpdateView(generic.UpdateView): model = Report def get_object(self): training = get_object_or_404(Training, date=self.kwargs["date"]) report = get_object_or_404( Report.objects.select_related("training") .prefetch_related("training__signups__pilot") training=training, ) return report def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... runs_by_signup = {} for signup in self.object.training.selected_signups: runs_by_signup[signup] = [...] context["runs_by_signup"] = runs_by_signup return context and in the corresponding template I call signup.pilot like so: {% for signup, runs in runs_by_signup.items %} <tr> <td class="text-nowrap">{{ signup.pilot }} ... </td> </tr> {% endfor %} However, each signup.pilot results in a call to the database to figure out the corresponding pilot. Is there a way to avoid these extra calls or do I have to store all information in get_context_data? -
Django IntegrityError in Admin Panel for Custom User Model
I'm facing an issue with Django's admin panel while trying to manage a custom user model. I have created a Customers model for user registration and management, separate from the built-in User model. However, when I try to access the admin panel to view, edit, or delete user entries, I encounter an IntegrityError related to the django_admin_log table from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, using=None, **extra_fields): user=self.create_user( email=self.normalize_email(email), password=password ) user.is_admin=True user.is_active=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): user_id = models.AutoField(primary_key=True) user_name = models.CharField(max_length=100) first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) email = models.EmailField(unique=True) password = models.CharField(max_length=100) company_name = models.CharField(max_length=200, blank=True, null=True) contactno = models.IntegerField(blank=True, null=True) address = models.TextField(blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) state = models.CharField(max_length=100, blank=True, null=True) zip = models.CharField(max_length=20, blank=True, null=True) country = models.CharField(max_length=100, blank=True, null=True) profile_picture = models.CharField(max_length=200, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) last_login = models.DateTimeField(blank=True, null=True) date_joined = models.DateTimeField(auto_now_add=True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name'] class … -
Download files with Django
I want to be able to download files on my Django website by clicking on a link. But even by following some tutorials it's not working. So first, I have a function that is generating files when I click on a button. This function is working fine, this is not the problem. So those files are being displayed on the page, and this is also working fine. So the problem is very about the downloading part.The page that is displaying the files name as links This is the function that is rendering the page and that is returning a list with all the files in a directory. And then the other part of this function is supposed to let me download the files by cliking their link. # views.py def print_ip(request, filename=''): if request.method == "POST": get_ipfile(request) ip_files_list = os.listdir("mysite/ip_print_files/") if filename != '': filepath = "mysite/ip_print_files/" + filename path = open(filepath, 'rb') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response else: return render(request, "print_ip.html", {"files": ip_files_list}) And this is the html file of the page shown in the previous image. Like you can see in the image above, the files name … -
JavaScript async/await polling to get a status - function doesn't return the correct data
Context: asynchronous tasks management in Django with Celery and Redis. I have a function that sends a POST request in Ajax. The server returns a task id. With the task id I launch another function just after the POST request to fetch the task status in order to check if the worker has executed the task successfully. Problem: I succeed in doing the polling with javascript and log the results. But at the end my function doesn't returns the correct data (the one in the if statement). It's as if the object returned by the if statement is ignored. It's the first time I write such a function. Any help would be much appreciated 🙏 Code function cancelSimcard() { const cancellationLink = document.getElementById("cancellationLink"); return { notificationOpen: false, message: "à remplacer", async sendCancellationRequest() { const data = await fetch(cancellationLink.dataset.url, { method: "POST", }); const result = await data.json(); const status = await getStatus(result.task_id); }, }; async function getStatus(task_id) { const statusData = await fetch(`/parc/task_status/${task_id}`, { method: "GET", }); const statusResult = await statusData.json(); if (statusResult.task_status === "SUCCESS") { console.log("DATA FROM SUCCESS BLOCK", statusResult); return statusResult; } else { await new Promise((resolve) => setTimeout(resolve, 1000)); await getStatus(statusResult.task_id); } console.log("DATA AT THE END", … -
Django form.is_valid() results in False, Not sure what is the cause
I'm currently doing CS50w,in project 1 it's assign to create a sort of wikipedia like site, user should be able to create new entries for that wiki and edit existing ones, this is where I got stuck. On each of the entries page there's a 'edit' button, whe user clicks it he's redirected to 'editEntry' function seen in code below, then user should be able to edit existing text and press submit, but however I edit the entry the form.is_valid() returns false and I'm not sure why. I'm asking for tips, not straight answer because I really want to learn this, I'm confused because even print(form.errors) outputs blank line. Sorry if this is asked incorectly, it's my first question ever on this site and english is not my first language. Thank you class editPageForm(forms.Form): def __init__(self, entry_data, *args, **kwargs): super(editPageForm, self).__init__(*args, **kwargs) self.fields['markdown'] = forms.CharField( widget=forms.Textarea(), initial=entry_data ) def editEntry(request,entry): if request.method == "POST": # Take in the data the user submitted and save it as form form = editPageForm(request.POST) print('Printing Form') print(form) print('Printing Form non field errors') print(form.non_field_errors) # Check if form data is valid (server-side) if form.is_valid(): print('Valid') title = entry new_markdown = form.cleaned_data['markdown'] entryFile = open(f'./entries/{entry}.md', 'w') … -
Django admin Editing a product with properties and property types
I have a 3 models: class Product(models.Model): ... properties = models.ManyToManyField(PropertyVar, blank=True) class Property(models.Model): name = models.CharField(max_length=256, blank=True, default='') class PropertyVar(models.Model): value = models.CharField(max_length=256, blank=True, default='') property = models.ForeignKey(Property, on_delete=models.CASCADE, null=True, blank=True) How to make it possible in the admin panel to add/edit for the product (Product) properties (PropertyVar) with a choice of property type (Property)? Thanx! filter_horizontal just displays all propertyVar in a row... It becomes unclear which property these propertyVar refer to...