Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Managing Django Model Class for Workout Application
I am building up a workout progress application for a learning project. When setting the class model for the project I came across to schools of thought and I don't know what is the advantages and disadvantages for reach. Here is the simply version: class Exercise(models.Model): name = models.CharField(max_length = 30) def __str__(self): return self.name class Set(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='sets') weight = models.FloatField(validators=[MinValueValidator(0)]) repetitions = models.IntegerField(validators=[MinValueValidator(1)]) def __str__(self): return self.exercise.name + ' set #' + str(self.pk) and the second more complicated is: class Exercise(models.Model): # Attributes name = models.CharField(null=False, blank=False, max_length=100) # Methods def __str__(self): return self.name class ExerciseSet(models.Model): # Attributes for exercise sets exercise = models.ForeignKey(Exercise, null=False, blank=False, on_delete=models.CASCADE) sets = models.ManyToManyField("my_gym.Set", related_name="sets") number_of_sets = models.IntegerField(null=False, blank=False, default=3) # Methods def __str__(self): return str(self.exercise.name) + " - " + str(self.number_of_sets) + " sets" class Set(models.Model): # Attributes reps = models.PositiveIntegerField(null=False, blank=False, default=0) weight = models.DecimalField(max_digits=5, decimal_places=2) # Methods def __str__(self): return ( str(self.reps) + " " + " x " + str(self.weight) + " " ) The requested project outcome is to just to set the progress of the workout logging the weight and reps of each excercise. My question is which is the more preferred and … -
Why my function in django to change a BooleanField is not working?
I'm trying to change a BooleanField from a model in django, using the post method activated with a button but is not working, the post method from de button is working but the function is not doing what it should do. When i change the boolean value in the admin tool it's work, i think probable the problem is in the function but i don't know whats is the problem. this is my function: def close(request, listing_id): listing = Listing.objects.get(id=listing_id) if request.method == "POST": listing.active = False listing.save() messages.success(request, 'You closed the Auction!') return redirect(reverse("listing", args=[listing_id])) The BooleanField whats i want to change it's call "active" (true by default). and this is the button: <form action="{% url 'close' listing.id %}" method="post" > {% csrf_token %} <button type="submit" name="action" value="close" class="btn btn-warning mb-3">Close Auction</button> </form> -
Django send_mail redirection
I am trying to include an anchor tag in the email that redirects to the request detail, but it is giving me this error when I click on the link This is how I sent the mail: from django.core.mail import send_mail from django.conf import settings from django.template.loader import render_to_string send_mail( subject='Request Rejected', message=f'Your request has been rejected by {self.request.user.username}.', from_email=settings.EMAIL_HOST_USER, recipient_list=[self.get_object().student.email], html_message=render_to_string('request/request_mail.html', {'content': f'Your request has been rejected by {self.request.user.username}.', 'obj':self.get_object()}) ) The request_mail.html: <!DOCTYPE html> <html lang="en"> <head></head> <body> <p>{{ content }}</p> <a href="{% url 'request-detail' obj.id %}">Click here to view details of the request</a> </body> </html> -
How to add constant fields to Wagtail form builder
I have created job application form with Wagtail form builder. Now I need to add some fields which are meant to be constant and appear on the application form without the need for the admin user adding them each time a new job application form is created. For instance, I have the following: Name Email Phone Number [admin created form fields] How to instantiate the first 3 fields and populate FormField db table with the data before the JobApplicationForm page is created? My data as below: FormField( question = 'Enter Your Name', label = 'name', field_type = 'singleline', required = True, ), I have the feeling a signal has to be created, but I don't know how? -
Applying different CSS style for each element in For Loop - Django
I'm building a blog with Django and i'm trying to apply my static design to dynamic HTML templates. I have several CSS classes for diffrenet card types (regular, medium and large), and i'm builing a posts page that should display all posts from all classes. I'm trying to find a solution for looping through every post and applying different CSS class accordingly. To sum it up: i have a posts list in my db i want to loop over all the posts and assign different pre-defined CSS class to different posts (meaning the "class" should be different for some posts, some should have class "card" and some "large-card", etc) Any help? Here is a sample of the html code i refer to: {% for post in post_list %} <div class="card"> ... </div> {% endfor %} -
How to convert sql-script to python(django-rest-framework)
i have two tables class Events(models.Model): install_time = models.DateTimeField() event_time = models.DateTimeField(primary_key=True) appsflyer_id = models.CharField(max_length=255, blank=True) media_source = models.CharField(max_length=255, blank=True) campaign = models.CharField(max_length=255, blank=True) platform = models.CharField(max_length=255, blank=True) event_name = models.CharField(max_length=255, blank=True) event_revenue = models.DecimalField(max_digits=30, decimal_places=10, blank=True) event_revenue_usd = models.DecimalField(max_digits=30, decimal_places=10, blank=True) class Installs1(models.Model): install_time = models.DateTimeField() event_time = models.DateTimeField(primary_key=True) appsflyer_id = models.CharField(max_length=255, blank=True) media_source = models.CharField(max_length=255, blank=True) campaign = models.CharField(max_length=255, blank=True) platform = models.CharField(max_length=255, blank=True) event_name = models.CharField(max_length=255, blank=True) event_revenue = models.DecimalField(max_digits=30, decimal_places=20, blank=True) event_revenue_usd = models.DecimalField(max_digits=30, decimal_places=20, blank=True) and have SQL-script with a as ( select campaign , sum(event_revenue) as event_revenue_sum, sum(event_revenue_usd) as event_revenue_usd_sum from events e where e.event_time::date between '2020-06-11' and '2020-06-16' group by campaign ), b as ( select campaign, count(event_name) as count_installs from installs1 i group by campaign ) select * from a left join b on a.campaign = b.campaign i don't understand how to convert this to django code to display in view and not full This is my view, but it dosent work class ReportsView(ListAPIView): queryset = Events.objects.all() serializer_class = ReportsGenerationSerializer def get_queryset(self): return Events.objects.aggregate(event_revenue_sum = Sum('event_revenue'), event_revenue_usd_sum = Sum('event_revenue_usd')) my serializer class ReportsGenerationSerializer(serializers.Serializer): event_revenue_sum = serializers.IntegerField() event_revenue_usd_sum = serializers.IntegerField() class Meta: model = Events fields = ('campaign', 'event_revenue_sum', 'event_revenue_usd_sum') How do I … -
mkvirtualenvwrapper error does not make sense
I upgraded my system from Ubuntu 18.04 to 20.04. On the 18.04 system, I had no issues creating virtual environments. I have an existing Django project and I am trying to create a virtualenv with a new python version, 3.8. But now, I have run into a snag. My session: $ mkvirtualenv -a /home/mark/python-projects/new_hopirockets_website -p /usr/bin/python3.8 new_hopi_rockets_website ERROR: virtualenvwrapper could not find /usr/share/virtualenvwrapper/virtualenvwrapper.sh in your path $ echo $PATH /usr/local/lib/nodejs/node-v12.4.0-linux-x64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/share/virtualenvwrapper $ ls -alh /usr/share/virtualenvwrapper/virtualenvwrapper.sh -rw-r--r-- 1 root root 41K Sep 3 2019 /usr/share/virtualenvwrapper/virtualenvwrapper.sh $ export PATH=$PATH:/usr/share/virtualenvwrapper/virtualenvwrapper.sh $ echo $PATH /usr/local/lib/nodejs/node-v12.4.0-linux-x64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/share/virtualenvwrapper:/usr/share/virtualenvwrapper/virtualenvwrapper.sh $ mkvirtualenv -a /home/mark/python-projects/new_hopirockets_website -p /usr/bin/python3.8 new_hopi_rockets_website ERROR: virtualenvwrapper could not find /usr/share/virtualenvwrapper/virtualenvwrapper.sh in your path $ /usr/bin/python3.8 Python 3.8.10 (default, Jun 22 2022, 20:18:18) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> $ ls /home/mark/python-projects/new_hopirockets_website articles fred new_hopi_rockets_website.wpr run.sh bugs_new_hopirockets_website.ods full_text_search new_hopi_rockets_website.wpu sam.txt check.txt gallery old_gallery3 setup contact get_archive_data_from_tsunami.sh 'old stuff' simulation cp_tsunami-hopirockets_to_octopus.sh hit_counters payload_separated.txt soft-ui-dashboard cp_tsunami_to_octopus.sh hopirockets __pycache__ static database __init__.py README.txt test.sh DataTables launchdate requirements utils flights manage.py rsync_logs viewcount $ I am not sure what is going on here. Thanks in advance for your help! -
UNIQUE constraint failed: members_activemember.member_id onetoonefield Django
I get this error message. I am not sure why? It says it's coming after saving my form from the update function in my views.py file. Integraty Error: IntegrityError at /update/8 UNIQUE constraint failed: members_activemember.member_id Request Method: POST Request URL: https://topxgym.pythonanywhere.com/update/8 Django Version: 4.1 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: members_activemember.member_id Exception Location: /home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 357, in execute Raised during: members.views.update Python Executable: /usr/local/bin/uwsgi Python Version: 3.9.5 Python Path: ['/var/www', '.', '', '/var/www', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages', '/home/topxgym/.virtualenvs/env/topxgym'] Server time: Tue, 23 Aug 2022 00:55:22 +0300 TrackBack Environment: Request Method: POST Request URL: https://topxgym.pythonanywhere.com/update/8 Django Version: 4.1 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'members', 'authenticate'] 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 "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) The above exception (UNIQUE constraint failed: members_activemember.member_id) was the direct cause of the following exception: File "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/topxgym/.virtualenvs/env/topxgym/members/views.py", line 196, in update form.save() File "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/forms/models.py", line … -
DJango not excuting Javascript loaded from a file
I'm learning by examples and tried a code by @furins. The code works when the button is clicked, it calls the javascript function. But when I separate the javascript into a separate file static/js/test.js, it doesn't do anything. http://localhost:8080/static/js/test.js shows the script text, so static directory is working. What am I missing? *** original *** <html> <head> <title>An example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> function call_counter(url, pk) { window.open(url); $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) { alert("counter updated!"); }); } </script> </head> <body> <button onclick="call_counter('http://www.google.com', 12345);"> I update object 12345 </button> <button onclick="call_counter('http://www.yahoo.com', 999);"> I update object 999 </button> </body> Separated: *** base.html *** {% load static %} <html> <head> <title>An example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="{% static 'js/test.js' %}"></script> </head> <body> <button onclick="call_counter('http://www.google.com', 12345);"> I update object 12345 </button> <button onclick="call_counter('http://www.yahoo.com', 999);"> I update object 999 </button> </body> *** static/js/test.js *** function call_counter(url, pk) { window.open(url); $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) { alert("counter updated!"); }); } -
Use TokenAuthentication AND SocialAuthentication from AllAuth
I've created a new Django Rest API thanks to Django Rest Framework and I want to use two type of authentication : TokenAuthentication AND SocialAuthentication with two providers Facebook and Google. Token authentication is success (with this syntax : Authorization: Token <token>. However, I can't get it to work with the SocialAuthentication. When I get the access_token from my POST in GoogleSocialLoginView, I can't use it to login in my others API call headers (I use an authenticated permissions for others CRUD calls). My syntax for social authentication is : Authorization : Bearer <token> So the users are registered successfully in database, but they can't authenticated us to the API after. This is a part of my settings.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_swagger', 'rest_framework.authtoken', "dj_rest_auth", 'dj_rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', # Local apps we created 'api', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'thetiptop.urls' AUTH_USER_MODEL = 'api.Users' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS':'rest_framework.schemas.coreapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } REST_AUTH_SERIALIZERS = { "LOGIN_SERIALIZER": "api.serializers.CustomLoginSerializer", } REST_USE_JWT = True ACCOUNT_LOGOUT_ON_GET = … -
How does Django work with react combined?
I just started out with Django, I got a litte bit experience in React though. So, there is one topic that confuses me a litte... If I google how Django works with React, I mostly see 2 ways. The first on works by putting React right into Django and the second is by using a Rest-API. I Think that the two ways follow different approaches in terms of that the first way is for using React directly in the backend (so as a part of the backend) and the second option uses React in the Frontend and communicates via the API with the backend. IF I am wrong at this point then please show me the right way... So, IF I am right, what is the goal of using React inside of Django, if you already have the possibilities of using variables, functions or even classes? Just because of JS instead of Python? Or do I overlook something? -
Displaying Comment Form in Django 401 Error
I am trying to build a CRM in Django and in doing so I am trying to add a place to add comments to a lead. I created a form and upon submitting a comment I get directed to the 401 page where I am greeted with an error. On the 401 page it references my form.save() in my views. Please help. 401 Error "Field 'id' expected a number but got 'some'." . I will post my code below Below is my info view which is used to display information about a particular lead def info(request, pk): info = lead.objects.get(id=pk) form = lead_comment() if request.method == 'POST': form = lead_comment(request.POST) if form.is_valid(): form.save() return redirect('info.html') context={'info':info, 'form': form} return render(request, 'info.html', context) My URLS from django.urls import path from . import views urlpatterns = [ path('', views.dashboard, name='dashboard'), path('leads/', views.leadsPage, name='leads'), path('docs/', views.docsPage, name='docs'), path('add-lead/', views.addLead, name='add-lead'), path('leads/<str:pk>/', views.info, name='description'), ] My info.html {% include 'navbar.html' %} <body class="dash"> <div class="navdash"> <div class="container-lead"> <div class="lead-space"> <h2>{{ info.first }} {{ info.last }}</h2> <h5>Phone number: {{ info.phnum }}</h5> <h5>Email: {{ info.email }}</h5> </div> <body> <form method="POST" action=""> {% csrf_token %} {{ form }} <input type = "submit" value = "Submit" /> </form> … -
Django/ Javascript : Custom the visual of adropdown menu a form.ChoiceFiled
I have an app with a form that is split in several steps with FormWizard.Some fields are multichoice fields with thousands of choices. I want to improve the presentation of the dropdown menu. I would like to replace it by a kind of fixed list with a scrollbar, like that few data is always displayed and the user sees it wihout clicking on the dropdown to show it. However I do not know how to do that, if it is with Javascript or CSS. I create the form wiht django and I call it. Anyone can help me or show me an example ? forms.py class ClientForm1(forms.Form): client = forms.ChoiceField(label="Client :") def __init__(self, uuid_contrat, *args, **kwargs) : super(ClientForm1, self).__init__(*args, **kwargs) id_contrat = Entity.objects.all().filter(uuid=uuid_contrat).values_list('id', flat=True)[0] client_choices = Toriiclients.objects.filter(idcustomer=id_contrat).order_by('-id').values_list('id', 'prenom') self.fields['client'].choices = client_choices class SaletypeForm2(forms.Form): saletype = forms.ChoiceField(label="Client :") information =forms.CharField(max_length=1000) def __init__(self, uuid_contrat, *args, **kwargs) : super(SaletypeForm2, self).__init__(*args, **kwargs) id_contrat = Entity.objects.all().filter(uuid=uuid_contrat).values_list('id', flat=True)[0] client_choices = ToriiLstAffairetype.objects.filter(idcustomer=id_contrat).order_by('-id').values_list('short_desc', 'short_desc') self.fields['saletype'].choices = client_choices views.py from django.shortcuts import render from .forms import ClientForm1, SaletypeForm2 from formtools.wizard.views import SessionWizardView class FormWizardView(SessionWizardView): template_name = "sales/formwiz.html" form_list = [ClientForm1, SaletypeForm2] def get_context_data(self, form, **kwargs): context = super(FormWizardView, self).get_context_data(form, **kwargs) uuid_contrat = self.kwargs['uuid_contrat'] id_contrat = Entity.objects.all().filter(uuid=uuid_contrat).values_list('id', flat=True)[0] context['last_clients_created'] = … -
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. router.py given
database setting I know settings.DATABASES is correctly configured as I've already created models which then Django used to create tables in the DB but for whatever reason it is now causing this error. You can also see that I have already "supplied the ENGINE value". and router.py one more thing first database customer I did not get any error during makemigration command and successfully created table in database DATABASES ={ 'default': {}, 'users':{ 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'customer', 'USER': 'postgres', 'PASSWORD': '123', }, 'listings':{ 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'listing', 'USER': 'postgres', 'PASSWORD': '123', }, } DATABASE_ROUTERS = ['customer.router.AuthRouter', 'list.router.ListingRouter'] router.py class ListingRouter: route_app_labels = {'listing'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'listings' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'listings' return None def allow_relation(self, obj1, obj2, **hints): if (obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'listings' return None database setting and router.py attached 1 2 -
Django multi user handling
i’m writing an app which a user can calculate some values and get a graph from them. I’m thinking now what is happen when multiple users fire a request for calculating? I can store variables in session but I’m not sure what is happen when multiple user firing a method at the same time. Eg. def calc(self,x,y): test = [] test.append(…) -
Django ImproperlyConfigured error with django-admin-csvexport
So I have been working on adding an admin function to a Django project so that I can export the model instances to csv. It is all working fine locally whilst using Docker. But when deploying it to the server it doesn't work. When I activate the virtualenv (source /home/vfs/.cache/pypoetry/virtualenvs/vfs-gOLk6wo--py3.7/bin/activate) and try to import the csvexport module I get this error: I've been looking on the internet for quite some time now and can't find a solution. I took over this project and wasn't involved in the server set up or anything. As I'm not that specialized in server side stuff I would appreciate it a lot if someone could help me with this. settings.py: INSTALLED_APPS = [ ... 'csvexport', ] model: from csvexport.actions import csvexport from django_summernote.admin import SummernoteModelAdmin class FundAdmin(SummernoteModelAdmin): ... actions = [csvexport] manage.py #!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) -
How to save email as lower case in django while signing up user?
I want to turn emails to lower case while signing up a new user, i have tried doing it using the lower() method, but it does not automatically sign in the user using the login() function. Maybe i am not doing it the right way? Now what would be the right way to achieve this? NOTE: I would post the full Code def registerRef(request, *args, **kwargs): if request.user.is_authenticated: return redirect('core:index') profile_id = request.session.get('ref_profile') print('profile_id', profile_id) try: signup_point = SignUpPoint.objects.get() except: signup_point = None code = str(kwargs.get('ref_code')) try: profile = Profile.objects.get(code=code) profile_user = Profile.objects.get(code=code) request.session['ref_profile'] = profile.id print('Referer Profile:', profile.id) except: pass print("Session Expiry Date:" + str(request.session.get_expiry_age())) form = UserRegisterForm(request.POST or None) if form.is_valid(): if profile_id is not None: recommended_by_profile = Profile.objects.get(id=profile_id) ref_earn = InvestmentPackageID.objects.get() instance = form.save(commit=False) instance.email = instance.email.lower() instance.username = instance.username.lower() instance.save registered_user = User.objects.get(id=instance.id) registered_profile = Profile.objects.get(user=registered_user) registered_profile.recommended_by = recommended_by_profile.user my_recomended = Profile.objects.filter(recommended_by=profile_user.user).values_list('user__id', flat=True) print(my_recomended) # second_level_recommended=Profile.objects.filter(recommended_by__in=my_recomended) registered_profile.save() profile = Profile.objects.get(user=registered_user) profile.earning_point = signup_point.signup_point profile.main_all_earning += signup_point.signup_point profile.save() if recommended_by_profile.level_1 == True and recommended_by_profile.level_6 == False and recommended_by_profile.level_5 == False and recommended_by_profile.level_4 == False and recommended_by_profile.level_3 == False and recommended_by_profile.level_2 == False: recommended_by_profile.referral_point = recommended_by_profile.referral_point + ref_earn.ref_earn1 recommended_by_profile.main_all_earning = recommended_by_profile.main_all_earning + ref_earn.ref_earn1 recommended_by_profile.save() else: recommended_by_profile.referral_point = recommended_by_profile.referral_point … -
UnboundLocalError at /update-skill
I can't figure out why I can't fix this code after reading other people's similar issues. When I click the Edit Skill icon on my site, I get this Error Message: UnboundLocalError at /update-skill/39152d45-8e94-4982-9f36-16cbd96d80f7/ local variable 'profile' referenced before assignment The code I have for the EditSkill looks like this: @login_required(login_url='login') def editAccount(request): profile = request.user.profile form = ProfileForm(instance=profile) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save() return redirect('account') context = {'form': form} return render(request, 'users/profile_form.html', context) I've looked at the code repeatedly and clearly can't pinpoint my error. Advice would be excellent! Thanks! -
I can’t save form in database, sqlite3
I can’t seem to save anything to database,it returns, the code works fine. It redirect me to the url after the save function is called but nothing in database, I tried checking like this obj = form.save() print(f'saved object with pk={obj.pk}') It returned “Save object with pk=None” -
Django do not update ImageField
Why Django update() do not update image file in media folder, but update everything else in update process.. Old image is in media folder, but there is no new image in folder.. When creating (using save()) everything is fine.. Any help, thanks in advance... Here is the model class: class Company(models.Model): name = models.CharField(max_length=100) companyAddress = models.CharField(max_length=70) companyPhoneNumber = models.CharField(max_length=30) companyDescription = models.CharField(max_length=150) companyProfileImage = models.ImageField(upload_to='images/', default = "images/defaultCompany.jpg", null = True) Here is the code that I use when update: newName = request.data['name'] newAddress = request.data['address'] newPhoneNumber = request.data['phoneNumber'] newDescription = request.data['description'] newCompanyProfileImage = request.data['image'] Company.objects.filter(id = companyId).update(name = newName, companyAddress = newAddress, companyPhoneNumber = newPhoneNumber, companyDescription = newDescription, companyProfileImage = newCompanyProfileImage) -
ModuleNotFoundError: No module named 'django.contrib.'
I'm getting this weird error when I'm trying to run my Django project, more details (Social_Media is the project's name): ModuleNotFoundError: No module named 'django.contrib.' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "E:\= Programming Office\Django Projects\Social_Media\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "E:\= Programming Office\Django Projects\Social_Media\lib\site-packages\django\core\management\commands\runserver.py", line 157, in inner_run handler = self.get_handler(*args, **options) File "E:\= Programming Office\Django Projects\Social_Media\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 31, in get_handler handler = super().get_handler(*args, **options) File "E:\= Programming Office\Django Projects\Social_Media\lib\site-packages\django\core\management\commands\runserver.py", line 78, in get_handler return get_internal_wsgi_application() File "E:\= Programming Office\Django Projects\Social_Media\lib\site-packages\django\core\servers\basehttp.py", line 49, in get_internal_wsgi_application raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'Social_Media.wsgi.application' could not be loaded; Error importing module. wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Social_Media.settings') application = get_wsgi_application() Can anyone help me? -
I need to open the response which is video url in separate page
For this one I get response in a separate page as text, I need to convert this text into a url so that when I click that button it redirects to that page. const getData = () => { try{ axios.get(`${geturl}`,{ }).then(res=>document.write(res.data.result.content.previewUrl)); }catch(err){ console.log(err.message); }; -
Django REST Framework Serializer - how to save InMemoryUploadedFile to disk?
At my Django RestAPI I can upload an image, instead of saving this image at an ImageField referenced at the database I just want to save it to the disk without any further processing. Currently, my code looks like this: class UserAvatarUpdateSerializer(ClearNullSerializer, serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) avatar = serializers.ImageField(write_only=True, required=True) class Meta: model = get_user_model() fields = ('id', 'user', 'avatar',) read_only_fields = ('id', 'user') def save(self, **kwargs): new_avatar = self.validated_data['avatar'] directory = (str(MEDIA_ROOT) + "tmp/") filename = str(uuid.uuid4()) new_avatar.save(os.path.splitext((directory + filename))[0] + '.png', optimize=True, format='png') But I'm running into: AttributeError: 'InMemoryUploadedFile' object has no attribute 'save' So my question is how can I save a InMemoryUploadedFile to disk? -
How to access data in Docker from my Django app?
I am new to Docker so I wonder if I have 2 containers, a streamer that pushes data to the queue and vernemq which is the message queue. How can I access the data to work with it in my django rest api app? I was wondering is there a way to export or the data and create a separate database in django with it or it's not how it works? Or is there a way to directly access the data in docker from django app. Note the django rest api app is not in a docker Image. -
Make first name field unique for User in django
I am making a web app with django and I need to make the Users first name unique. I have searched around and it doesnt seem like there is a simple way to do this. The reason i need the first name to be unique is because i am using the first name field as a spotify username field because it makes it convenient because i can use the user creation form.