Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix Django models migrate error for image field?
I am putting an image field in a model called Students. Everything is working fine until I put an image field into the model. I am getting the following even I put blank and null as True. It should work fine. Following is the detail information. Error django.db.utils.IntegrityError: NOT NULL constraint failed: new__genius_students.image This is the model models.py class Students(models.Model): created_by = models.ForeignKey( User, on_delete=models.SET_NULL, default=1, null=True) name = models.CharField(max_length=200, null=True) image = models.ImageField(upload_to='images/', null=True, blank=True) dob = models.DateField(null=True, verbose_name='Date of Birth') age = models.IntegerField() I had tried many things like clearing cache and cookie. But No luck. -
How to implement like/dislike button (for logged-in users) in django using AJAX
I tried implementing Like(for those users who didn't like) and Dislike(for users who already liked the post) buttons but I could not get it to work. I tried looking some past questions but I could not solve the issue. If someone has done this before, kindly help. my blog/models.py for Post model class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def total_likes(self): return self.likes.count() my blog/views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True return render(request, 'blog/post_detail.html', {'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), }) def like_post(request): post = get_object_or_404(Post, id=request.POST.get('id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True context = { 'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), } if request.is_ajax(): html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) my HTML and AJAX code (this section is present in post_detail.html) <div id="like-section"> {% include 'blog/like_section.html' %} </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script type="text/javascirpt"> $('#like').click(function(){ var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: "like_post", data: { 'id':pk, }, success: function(response){ $('#like-section').html(response['form']) }, }); }); </script> like-section.html is a separate template :- <p>{{ total_likes }} Like{{ … -
How to make a div appear after post request and stay same page
I am trying to register and verify number in the same page. When I send post request to register there is phone field in data. Then view sends verification code to the this number. Now I want stay same page and make the confirm div appear after register request and confirm the verification code with appeared div. https://imgur.com/f3pGkN2 https://imgur.com/bOHhXMK -
Django: When print a QuerySet gives an error
I have a table(SavedSchedules) below in the database. hall_n_time and schedule columns stores two python lists as string. +----+---------------+-------------+----------+ | id | lecturer | hall_n_time | schedule | +----+---------------+-------------+----------+ |... | ... | ... | ... | +----+---------------+-------------+----------+ I have below script in views.py: lec_name = User.objects.filter(username=request.session['logged_username']).values_list('lecturer_name', flat=True) print(lec_name) This gives OUTPUT: <QuerySet ['A. B. C. Watson']> But EXPECTED OUTPUT: A. B. C. Watson Then I tried below script: lec_name = User.objects.filter(username=request.session['logged_username']).values_list('lecturer_name', flat=True) schedule_data = SavedSchedules.objects.filter(lecturer=lec_name) print(schedule_data) It gives below ERROR when I execute it: Traceback (most recent call last): File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Web Projects\CIS_ALTG\altg\altg_app\views.py", line 497, in profile print(schedule_data) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 252, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 276, in __iter__ self._fetch_all() File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1124, in execute_sql sql, params = self.as_sql() File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 498, in as_sql where, w_params = self.compile(self.where) if self.where is not None else ("", []) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 415, in compile sql, … -
Use a code executing every hour in Django
I'm using Django for developing an app for booking cars, then I need an automated code to check if a car is booked automatically every hour, I'm new in Django and I don't have idea how to do this -
How to get data from ModelViewSet in DRF without calling an API call
I'm going to convert all my APIs into gRPC calls. At the moment I was able to transfer all the ViewSet into gRPC(sample code added end of this question). But ModelViewSet, it get an error like this. Traceback (most recent call last): File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/venv/lib/python3.6/site-packages/grpc/_server.py", line 435, in _call_behavior response_or_iterator = behavior(argument, context) File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/servicers/tenant/main.py", line 15, in get_tenant data = ClientViewSet().list(request=original_request, ) File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/common/lib/decorators.py", line 128, in wrapper_format_response final_data = call_func(func, self, request, transaction, exception, *args, **kwargs) File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/common/lib/decorators.py", line 99, in call_func return func(self, request, *args, **kwargs) File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/api_v1/viewsets.py", line 471, in list data = super().list(request, *args, **kwargs).data File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/venv/lib/python3.6/site-packages/rest_framework/mixins.py", line 38, in list queryset = self.filter_queryset(self.get_queryset()) File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/venv/lib/python3.6/site-packages/rest_framework/generics.py", line 158, in filter_queryset queryset = backend().filter_queryset(self.request, queryset, self) AttributeError: 'ClientViewSet' object has no attribute 'request' So my viewsets.py look like this (format_response decorator convert it to Response object) class ClientViewSet(viewsets.ModelViewSet): queryset = Client.objects.all() serializer_class = ser.ClientSerializer @format_response(exception=False) def list(self, request, *args, **kwargs): data = super().list(request, *args, **kwargs).data # data = {} return data, True, HTTPStatus.OK, 'data retrieve successfully' When I call this as an API, it works perfectly. But I want to do the same thing without calling an API. Here how I was solving it, from django.http import … -
Heroku app successfully deployed, but getting application error when loading site
can someone please help to get error in log files Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail Don't know what to do now -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.8.2 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput 130 static files copied to '/tmp/build_b1535ec053fdba9963297a3644bcd70a/staticfiles', 410 post-processed. -----> Discovering process types -----> Compressing... Done: 55M -----> Launching... Released v8 https://hwcount.herokuapp.com/ deployed to Heroku -
Django form validation on PIN number
I have a Integerfield in my ModelForm which should contains data between 100000 & 999999. Facing issues in validation. I tried lots of combinations , but doesn't help. from django.forms import ValidationError class myForm(forms.ModelForm): pin = forms.IntegerField(label="PIN : ", required=True) def clean(self): if self.cleaned_data.get('comppin') <= 999999 & self.cleaned_data.get('comppin') >= 100000: try: return int(self.cleaned_data['comppin'].strip()) except ValueError: raise ValidationError("Invalid number") from django.core.validators import MaxValueValidator, MinValueValidator class Company(models.Model): comppin = models.PositiveIntegerField( validators=[MinValueValidator(100000), MaxValueValidator(999999)]) Maybe I am doing something wrong. Need help in this step. -
Attempted relative import beyond top-level package with Python
I have seen several questions related to this error but I think they are different cases. My Django project has 2 applications and a directory structure like this and I'm facing an issue with relative imports I don't understand the logic. Python allows me to import market from file my_app2/signals.py but it returns ValueError: attempted relative import beyond top-level package if I import portfolio from file my_app1/signals.py. What is the reason and how can I found a wordaround? /my_project /my_project /my_app1 /market.py /signals.py # From this file I'd like to import portfolio.py /my_app2 /portfolio.py /signals.py Files content: my_app1/signals.py from ..my_app2 import portfolio # doesn't work my_app2/signals.py from ..my_app1 import market # works -
How do i validate a extended user's field against a secondary (not the default) database in Django?
forms.py: class CustomUserCreationForm(forms.Form): username = forms.CharField() email = forms.EmailField() personalid = forms.IntegerField() password1 = forms.CharField() password2 = forms.CharField() def clean_username(self): username = self.cleaned_data['username'].lower() r = CustomUser.objects.filter(username=username) if r.count(): raise ValidationError("There is a user with that username already!") return username def clean_email(self): email = self.cleaned_data['email'].lower() r = CustomUser.objects.filter(email=email) if r.count(): raise ValidationError("There is already a user with that email!") return email def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Password don't match!") return password2 def save(self, commit=True): customuser = CustomUser.objects.create_user( self.cleaned_data['username'], email = self.cleaned_data['email'], password = self.cleaned_data['password1'], personalid = self.cleaned_data['personalid'] ) return customuser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email','personalid') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields settings.py: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'default', 'USER': 'default', 'PASSWORD': 'defaultpassword', 'HOST': '127.0.0.1', 'PORT': '8243' }, 'secondary': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'secondary', 'USER': 'secondaryuser', 'PASSWORD': 'secondarypassword', 'HOST': '127.0.0.1', 'PORT': '11371' } I want to validate 'personalid' field against 'secondary', if 'personalid' exists in 'secondary', then the user can be created, else, prompt error message! Any help is well appreciated! Bless -
Django3 using MySQL - Read-and-update in single transaction
The default isolation level does not allow the following code to work; separate processes can read the same value, set the same value, and cause a miscount. def next_id(): with transaction.atomic(): db_counter = Counter.objects.filter(name=name).first() if not db_counter: # Create count if not exists db_counter = Counter.objects.create(name=name, count=0) count = db_counter.count db_counter.count = count + 1 db_counter.save() return count Some things I have looked at: Setting the isolation level to serializable works, but I fear that is too restrictive. The rest of the application is working just fine with repeatable read. The select_for_update might work, but I do not know how to apply it in the case there is no counter, and a record must be added. I have traced through the Django/MySQL code with the debugger: I am not certain transaction.atomic() does anything, I do not see it emit a START TRANSACTION. How do I ask Django to start a transaction? Thank you. -
Getting data from an API and not from Database
Morning, everybody, I'm an apprentice developer, and I have to develop a REST API with django. So far no problem. The trick is that I don't have to work from a database, but from a Python API in which I use functions that return the data I have to serialize. I put this schema here for you to better understand (the one on the right is the one used by my company) schema of API/DB/FRONT relation I have no problem to get datas and return them on endpoint, my problem is when I want to PUT, DELETE request. My DELETE request works with Postman, but when I trigger it from my forehead in sight, I get a 301 redirection error... For the other requests, I don't see how I can get the data from my form in my Vue Frontend and then pass it as an argument to the python function in Django which must insert it in the db ... Thanks in advance for your help Pixi -
Dose not appear to have any pattern in it
File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
ValueError: Field 'id' expected a number but got 'host'
Django returns me ValueError during migration. It expects ID. I'm new to Django btw. and it's my 3rd project. In others there is not such a problem with User Foreignkey. Can someone help me ? from django.db import models from django.contrib.auth.models import User class Room(models.Model): hosted = models.ForeignKey(User, on_delete=models.CASCADE, related_name="hosted_by") name = models.CharField(max_length=50, ) is_played = models.BooleanField(default = False) max_players = models.IntegerField(default = 4,) players_online = models.IntegerField(default = 1) players_ready = models.IntegerField(default=0) def __str__(self): return self.name -
Django form validation vs DRF serializer validation
I'm new to APIs creation in django. I checked DRF serializers and I found them useful when manipulating models in DB. My APIs don't use models they are based on forms. So my question is : what can I get more from using DRF validators then using django forms validators in my views ? maybe the content type is more convenient (application/x-www-form-urlencoded vs application/json) ? -
How can I access a Django models
I've three Django models ModelA, ModelB and ModelC. In my logic either an instance of ModelB or ModelC is associated with ModelA via a OneToOne relationship. I'd like to access the field of_interest via ModelAs backwards relationship to ModelB or ModelC. Is this possible? class ModelA(models.Model): ... class ModelB(models.Model): model_a = models.OneToOne( ModelA, related_name='%(class)s_model_a', of_interest=..., ... ) class ModelC(models.Model): model_a = models.OneToOne( ModelC, related_name='%(class)s_model_a', of_interest=..., ... ) -
Why isn't my for loop executing three times?
I expect three columns but the output gives only one column.It seems like the for loop is executing only once. This is my HTML code ''' <div class="row"> {% for head in heads %} <div class="col-lg-4"> <div class="single-bottom mb-35"> <div class="trend-bottom-img mb-30"> {% if head.latest %} <strong>Latest</strong> {% endif %} <img src="{{baseURL}}/{{head.img}}" alt=""> </div> <div class="trend-bottom-cap"> <span class="color1">{{head.head}}</span> <h4><a href="details.html">{{head.summ}}</a></h4> </div> </div> </div> {% endfor %} </div>''' This is views.py I have introduces three objects. ''' head2=News() head2.head='Coronavirus Updat' head2.summ='Deaths cross 2Lac World Wide' head2.img='2.png' head2.latest=True head2.id=False head3=News() head3.head='Coronavirus Updates' head3.summ='Deaths cross 2Lac World Wide' head3.img='2.png' head3.latest=True head3.id=False head4=News() head4.head='Coronavirus Updates' head4.summ='Deaths cross 2Lac World Wide' head4.img='3.png' head4.latest=False head4.id=False heads={head2,head3,head4} return render(request,"index.html",{'head1':head1,'heads':heads})''' The output prints only one column. I expect Three of them. -
Creation of slots at regular intervals
I need to create time-slots according to a number of songs. For example, s if my playlist has 5 songs then we create the time-interval of slots by the logic, 60/5 = 12 minutes in this example as the number of songs was 5 here. I also provide the start_time and end_time. Here if I provide start_time = 5:00 am and end_time = 6:00 am, total songs = 5 S1: 5:00 - 5:12 S2: 5:12 - 5:24 S3: 5:24 - 5:36 S4: 5:36 - 5:48 S5: 5:48 - 6:00 The Model consists of these three fields: class SlotCreate(models.Model): from_time = models.TimeField(max_length=255, blank=True, null=True) to_time = models.TimeField(max_length=255, blank=True, null=True) songs = models.ManyToManyField('Song') labelling = models.ForeignKey('Labelling',blank=True, null=True) I am checking whether the slot exists with the following query: SlotCreate.objects.filter(from_time=from_time,to_time=to_time,labelling=label).exists(): errors.append("The Slot already exists "+"\n") The problem here is if the user provides: Start_time = 5:00 End_time = 6:00 Total songs = 3 Then the slots already exist in the time interval given above as S1, S2, S3, S4, S5 are already there. The piece of code with which I check above fails to determine this case as S1: 5:00 - 5:20 S1: 5:20 - 5:40 S1: 5:40 - 6:00 Can anyone help … -
how to use name in filtered list to find their origin from model `Item`
class Item(): name=models.CharField(max_length=200) origin=models.CharField(max_length=200) class Condition1(): name=models.CharField(max_length=200) size=models.DecimalField(decimal_places=2,max_digits=1000) weight=models.DecimalField(decimal_places=2,max_digits=1000) a=Condition1.objects.filter(size__gt=20, weight__lt=10) when i print a as <table>{% for item in a%} <tr><td>{{ item.name}}</td></tr>{% endfor %}</table> it gives list as Item1, Item10, Item13 in table. so now i want to print their origin and i wrote: origin=Item.objects.filter(name__in=a) however it does not give me anything. I want to use name in filtered list a to find their origin from model Item. How to make it work. What i am missing? -
Django model: fetch last ForeignKey in one query
In Django models, I have two database models like: A(models.Model): .... b = models.ForeignKey(B, related_name='my_a') B(models.Model): .... Now, I would like to fetch all B, but have last A be fetched with the same query. so something like: B.objects.all().annotate(myA=fetch last A) I know for prefetch_related but it is too slow. how can I do it? -
How to feature toggle URLs dynamically in Django rest framework
I am working on a project where we use feature toggles to hide features until they are ready to be released. The pattern we have followed is to simply not route certain endpoints if the feature toggle is off. I.e in urls.py, we only include URLs in the urlconf if the toggle is on. But this means feature toggles only have an effect if the server is restarted. We'd like to be able to dynamically turn feature toggles on and off on a running server. It seems that the urlconf is only parsed at startup time so changes to it are not reflected without a reboot. I've tried making a middleware to block certain URLs based on the value of a feature toggle and that works but doesn't play nicely with the Swagger docs, which I also would like to reflect the state of the feature toggles. In general, it feels like I am fighting the system, which is usually a sign that I'm not approaching it from the right angle. So, how do people advise me to implement dynamic feature toggles of behaviour in Django? -
python django Failed to load my python function code
OS: Linux Debian (last build) Python: 3.7.7 64bit Django: 3.0 Apache2: 2.4.x I'm trying to run and test my Django project on Linux apache2 (Production-Environment ). I want to insert a record in DB via pymysql module (when the entered string by user is correct/incorrect (log)). Below function (check_usr()) works fine in Test-Environment (127.0.0.1:8000). But doesn't work in Production. I'm just seeing content of else section in validation() view via web browser. def check_usr (usernameee): result = subprocess.run(['........'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) result = result.stdout.decode('utf-8') if "successfully" in result: return "ok" elif "activation failed" in result: return "no" else: return "problem" @require_http_methods(["GET"]) def validation(request): usernameee = request.GET["usernameee"] result = check_usr(usernameee) db_connection("init") if result == "ok": args = (ap_ssid, ap_mac, "ok") db_connection("INSERT INTO splash_tble (ap_ssid, ap_bssid, ap_state) VALUES (%s, %s, %s)", args) return render(request, "router/validation.html", {"validation_state": "success"}) elif result == "no": args = (ap_ssid, ap_mac, "no") db_connection("INSERT INTO splash_tble (ap_ssid, ap_bssid, ap_state) VALUES (%s, %s, %s)", args) return render(request, "router/validation.html", {"validation_state": "failed"}) else: return render(request, "router/validation.html", {"validation_state": "problem"}) My config in /etc/apache2/sites-available/routers.conf: DocumentRoot /root/PycharmProjects/router WSGIScriptAlias / /root/PycharmProjects/router/captives/wsgi.py WSGIPythonPath /root/PycharmProjects/router <Directory /root/PycharmProjects/router> <Files wsgi.py> Order deny,allow Allow from all Require all granted </Files> </Directory> Alias /static/ /root/PycharmProjects/router/captive_splash/static/ <Directory /root/PycharmProjects/router/captive_splash/static> Order deny,allow Allow from … -
Django - issue displaying context
I would like in my user_profile.html template to filter only the jobs offers related to the category.1, instead here it doesn't display anything. I can't understand if the error is on my models or template. So, in the template it will be something like " if the user score is > 1, then display all the jobs offers that are related to that quiz". If you take the Data Science quiz, you should see only the Data science category offers. Hope I described the issue clearly. I've been working on the issue for days and still can't solve it. core/user_profile.html {% extends 'base.html'%} {% block content %} {% for category,score in categories_scores %} <div class="card"> <div class="card-header"> {{ category.1 }} Score </div> <div class="card-body"> <h5 class="card-title">CONGRATS!</h5> <p class="card-text"> Here your SCORE: </p> <a href="#" class="btn btn-primary">{{ score }}</a> {% if score > 1 %} {% if request.user == user %} <br> <br> <div class="progress"> <div class="progress-bar bg-success" role="progressbar" style="width: 99%" aria-valuenow="99" aria-valuemin="0" aria-valuemax="100"></div> </div> <p class="card-text"> Congratulations! Now you can apply to:</p> <br> {% for job in jobs %} {% if category.1 == job.categoria %} <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" … -
Django class variable not getting destroyed after response
I have a simple view and I am not getting what's wrong with the logic. I understand lists are mutable, but this it is returning the same object on every response. class IndexView(TemplateView): data = [] def get(self, request, *args, **kwargs): self.data.append(1) return HttpResponse((self.data, f" {id(self.data)}")) When ever I am refreshing the page, I am getting old values in list and same id of object. Output: First time page renders: [1] 139988074103112 Second time page renders: [1, 1] 139988074103112 Third time page renders: [1, 1, 1] 139988074103112 I am not able to figure out why it is happening. Please help me guys. -
Implement ChatFuel in Django
I'm working on a website that sells adventures. After the user purchases an adventure, he receives a link (or a token if necessary) that they can use to start the ChatFuel adventure. Do you have any idea on how to implement that? I'm using stripe for purchases and on the website.com/charge (it confirms that the purchase was successful) I want to show them a link as well