Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django's RegexValidator outside of models
I defined a regex validator using Django's built in library. I use it to validate my fields on my models. Like this: from django.core.validators import RegexValidator validate_alphanumeric = RegexValidator(r'^[a-zA-Z0-9]*$', 'Only alphanumeric characters are allowed.') class MyModel(models.Model): label = models.CharField(max_length=40, validators=[validate_alphanumeric]) However, how can I use it outside of my fields? Like lets say I want to validate the string 'Hello' using the validator, provided the validator is stored in a regular variable, instead of a model. The docs seemed pretty confusing. Thanks. -
Which is better to create a object using data migration or by using code?
I am creating an object like this through code: if not Abc.objects.filter(name='xyz').exists(): Abc.objects.create(username='xyz') but I can create it through data migration also: def create_myobj(apps, schema_editor): do stuff class Migration(migrations.Migration): dependencies = [ ('myapp', 'your last migration'), ] operations = [ migrations.RunPython(create_myobj) ] So which is a better choice? Thanks in advance. -
E0401:Unable to import 'django.db'
So i'm studying python crashcourse and after finishing the basics I jumped to the django project. I created a virtual env, installed django and created an app with manage.py startapp command. I use Visual Studio Code, and the problem is when I go to models.py it gives an error that it's unable to find django.db module unable to import error Now I understand this is because of the file structure, which is as per my research the correct one, and I followed the book carefully, however i don't know how to fix this and I feel that i'm missing something. This is my file structure for the virtual environment file structure Any idea how to fix it ? :) Thanks in advance -
Django upload several image files to website
I am using Django to develop web site. I am new in Django and meet a problem how to upload several images to server. On my web site i want allow user to add several items and images. I am using jquary to add new input form in web page if user need to add more than one item. model.py class Menu(models.Model): restaurant_id = models.PositiveIntegerField() item = models.CharField(max_length = 200) price = models.FloatField() on_plate = models.ImageField(upload_to = 'menu/on_plate', null = True) on_deliver = models.ImageField(upload_to = 'menu/on_deliver', null = True) forms.py class UploadToMenu(forms.ModelForm): class Meta: model = Menu fields = ('item', 'price', 'on_plate', 'on_deliver') views.py def add_menu(request): if request.method == 'POST': rest = Menu(restaurant_id = '1') form = UploadToMenu(request.POST, request.FILES, instance=rest) print(form) if form.is_valid(): form.save() return redirect(reverse('deliver:add_menu')) return render(request, 'deliver/menu.html') HTML template {%block content%} <script type="text/javascript"> var total = 0; function add_new_image(){ total++; $('<tr>') .attr('id','menu'+total) .css({lineHeight:'20px'}) .append ( $('<tb>') .attr('id','td_title_'+total) .css({paddingRight:'5px',width:'200px'}) .append( $('<input type="text" class="form-control"/>') .css({width:'500px'}) .attr('id','item'+total) .attr('name','item') ) ) .append ( $('<tb>') .attr('id','td_title_'+total) .css({paddingRight:'5px',width:'200px'}) .append( $('<input type="text" class="form-control"/>') .css({width:'100px'}) .attr('id','price'+total) .attr('name','price') ) ) .append ( $('<tb>') .attr('id','td_title_'+total) .css({paddingRight:'5px',width:'200px'}) .append( $('<input type="file" accept=".jpg,.gif,.png" />') .css({width:'500px'}) .attr('id','on_plate'+total) .attr('name','on_plate') ) ) .append ( $('<tb>') .attr('id','td_title_'+total) .css({paddingRight:'5px',width:'200px'}) .append( $('<input type="file" accept=".jpg,.gif,.png" />') .css({width:'500px'}) .attr('id','on_deliver'+total) … -
Django project with Apache , urls problem
I added WSGIScriptAlias /test C:\wamp64\bin\apache\apache2.4.27\htdocs\TEST\djangoProject\Project\wsgi.py it works for the home page only but once I try to access another page the /test disappear. where should I add it? -
Unresolved reference text python
def stopword(request): form = WordForm(request.POST) if form.is_valid(): text = form.cleaned_data['word'] return redirect('chat:stopword') args = {'form': form, 'text': text} return render(request, 'chat/stopword.html', args) I am getting an error in the code args = {'form': form, 'text': text} and if I remove the redirect it says local variable text might be referenced before assignment. -
What do I choose as web development framework for a python project (that uses libraries like panda, tensorflow etc)?
I have a project, written in Python 3 and which uses libraries like tensorflow. It takes a .docx as input and outputs another .docx after processing it. I want to put this project on a website. Do I need a web development framework like Django? Flask ? Or is it too "heavy" as the page will be really simple (but the code not) ? -
How to prevent heroku from serve the requsts twice?
I have a simple Django application which send me email when specific POST request trigger it , the problem is heroku duplicates the request so my application serve it twice . how can i prevent that ? note : i am using the free plan -
django foreign key relationships
models.py class Hub(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class User(AbstractUser): is_client = models.BooleanField(default=False) is_trainer = models.BooleanField(default=False) username = models.CharField('username', max_length=150, unique=True) email = models.EmailField(unique=True) hub = models.ForeignKey(Hub, on_delete=models.CASCADE, blank=True, null=True) hub_position = models.CharField(max_length=150, default="") mentor = models.ForeignKey('self', on_delete=models.CASCADE, blank=True,null=True) terms = models.BooleanField(blank=True, default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'terms'] def get_absolute_url(self): return reverse('student:dashboard', kwargs={'pk': self.pk}) Confused on how to design the models here. Each User can belong to exactly one Hub.A hub has one leader, many excoms and many members ,all of them belongs to User .The hubs are added from the admin side.Leader can accept hub joining requests from excoms and members. -
relogin after n minutes with django and jwt
I've been recently testing django and I discover every day django permissions and so on. However, I encountered a problem which I have not yet found a solution. In rest_framework_jwt you set the authentication class as follows. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', This will do a great work for the general purpose. However, I want the user to reidentify if it's entering an area with sensible information let's say 10 minutes after the user logged in. Thus, I would like to send a parameter to the Authentication class telling that the user is in a sensible information area. I don't mind forking the project and adapting it for my purposes, however I would like to know how to send the parameter from the view to the authentication class (in this case: rest_framework_jwt.authentication.JSONWebTokenAuthentication). -
Is django well suited to creation a webb quiz?
I would like to learn more about Python & Django by doing a project. I want to create a sort of webb quiz that would ask questions of the user, then combine all of the answers that I got, calculate it and bring up the best option/solution to their problem. For example: Like a quiz about what car you should buy, and then have the users choose alternatvies and give them the best answer/solution. Is this possible in Python and Django specifily, or should I begin with something else to really learn the more about them? Thank you! -
Create files in Django with user input
I am building a Django messaging app where each chat room has its own template, model and view. What I'm struggling with is figuring out a way for a user to create private chat rooms with user input. I wanted the user to specify details in a template form and when they click submit, the files will be generated to create the chat room. Or is there a better way to do this? Any suggestions will be appreciated. oh and I am using Django 2.1.2 with Python 3.6.5. Thanks -
Django how to make each member of ManyToMany field unique?
I'm working on a recruitment website for programmers where each user can complete programming cases online and see their results. Here is how I modeled my relationships ( I omitted many unimportant fields and kept only the interesting ones) : Here's my candidate class class Candidate(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) cases = models.ManyToManyField(Case) Here's my Case class class Case(models.Model): title = models.CharField(verbose_name="Titre", max_length=1000) test1_complete = models.BooleanField(verbose_name="Test 1 Complété", default=False) test2_complete = models.BooleanField(verbose_name="Test 2 Complété", default=False) test3_complete = models.BooleanField(verbose_name="Test 3 Complété", default=False) test4_complete = models.BooleanField(verbose_name="Test 4 Complété", default=False) I then created two candidates and a case on the user panel and linked the two users with the case through the ManyToMany field. the test complete boolean fields refer to wether or not the user completed each set of test for the current case. My problem is that each Candidate has the same Case object and thus if User1 completes test1 of the case then each User will have it set to true. My goal is that when I make changes on a Case stored in the ManyToMany field of a Candidate it will only make the changes for this one and not for everyone using this case. Does anyone have … -
Bulk action in a grid made in django
I have created a grid with ListView and added filters using django-filter's FilterSet. I am not sure how to perform/multiselect the objects which are listed in the grid. Basically I want to mimic the django-admin bulk action button(given by default). Any help will be deeply appreciated as I am on a deadline here! Thanks! -
Using django select_related with an additional filter
I'm trying to find an optimal way to execute a query, but got myself confused with the prefetch_related and select_related use cases. I have a 3 table foreign key relationship: A -> has 1-many B h-> as 1-many C. class A(models.model): ... class B(models.model): a = models.ForeignKey(A) class C(models.model): b = models.ForeignKey(B) data = models.TextField(max_length=50) I'm trying to get a list of all C.data for all instances of A that match a criteria (an instance of A and all its children), so I have something like this: qs1 = A.objects.all().filter(Q(id=12345)|Q(parent_id=12345)) qs2 = C.objects.select_related('B__A').filter(B__A__in=qs1) But I'm wary of the (Prefetch docs stating that: any subsequent chained methods which imply a different database query will ignore previously cached results, and retrieve data using a fresh database query I don't know if that applies here (because I'm using select_related), but reading it makes it seem as if anything gained from doing select_related is lost as soon as I do the filter. Is my two-part query as optimal as it can be? I don't think I need prefetch as far as I'm aware, although I noticed I can swap out select_related with prefetch_related and get the same result. -
PyCharm Django previous server still runs after opening new project
Steps to reproduce the problem: 1) Open 1st project. 2) py manage.py runserver (now I can see my Project_1 website in browser by adress http://127.0.0.1:8000/). 3) CLOSE project in PyCharm and open another project. 4) execute py manage.py runserver after opening 2nd project. 5) Refresh tab in browser... And WTF? I still see my 1st project page while I am already close it, opened another project and even RUNSERVER on 2th project. I MUST see on tab http://127.0.0.1:8000/ new project after runserver, but it does not work. Is it PyCharm bug or something else? I am using PyCharm Pro with the latest updates. -
what is Difference between timezone.now() and datetime.now() in Django?
I need to know about the basic difference between timezone.now() and datetime.now() in Django? -
how to slove vector map prombem in django
i am trying to get google map in registration form to make user to input their location i need google map but i get this map... https://i.stack.imgur.com/u317n.png and i am using this code......... from django.contrib.gis.db import models as gismodel from django.db import models class mapshow(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=100) city = models.CharField(max_length=50) location = gismodel.PointField(u"longitude/latitude", geography=True, blank=True, null=True) objects = models.Manager() def __unicode__(self): return self.name ` -
Getting the validation errors raised as a formatted dictionary in Django
In my Django models, I am raising some validation errors when things are not how it should be. I am doing this in my clean() method. It works nicely, however, if I want to save from my shell, I have to call the full_clean() method before hand, which is again fine. Its something like this: class MyModel(models.Model): ... def clean(self): if condition_1: raise ValidationError({"field_1" : "Error regarding field 1."}) if condition_2: raise ValidationError({"field_2" : "Error regarding field 2."}) super(MyModel, self).clean() Now, what I want is to call a method before saving my objects which returns the formatted errors, like so: mymodel.get_validation_errors() # Returns {"field_1" : "Error regarding field 1.", "field_2" : "Error regarding field 2."} Is it impossible to do with my current clean() setup? If not, what is the conventional way to get the errors? Thanks! -
Not able to logout user django authentication
I am working on a project where an organization will login and then logout if they want. But somehow logout functionality is not working. No redirect is happening and user is not able to logout. #urls.py urlpatterns = [ path('logout',views.user_logout,name = 'logout') ] #views.py def user_logout(request): if request.method == "POST": logout(request) return HttpResponseRedirect('login') #template: <a href="#" onClick="document.getElementById('logoutform').submit()" class="btn"> Logout</a> <form id="logoutform" method="POST" action="{% url 'logout' %}"> {% csrf_token %} <input type="hidden"> </form> Page just reloads and no redirect happens. -
Django migration emitting strange error message
While writing a Django migration the following error message came up: ValueError: Cannot use QuerySet for "MyModel": Use a QuerySet for "MyModel". while doing a filter mymodel_queryset = MyModel.objects.filter(.....) OtherModel.objects.filter(mymodel__in=mymodel_queryset)` -
Rewrite ordering field of CursorPagination in Serializer - Django Rest Framework
I have a serializer need to pagination using CursorPagination: class AudioSerializer(ModelSerializer): set = SerializerMethodField() class Meta: model = Audio fields = [ 'id', 'set', ... ] def get_voice_set(self, obj): request = self.context.get('request') qs = Set.objects.filter(audio=obj).order_by('-timestamp') CursorSetPagination().ordering = '-timestamp' // This line paginator = CursorPagination() page = paginator.paginate_queryset(qs, request) serializer = SetListSerializer(page, context={'request': request}, many=True) if page is not None: res = paginator.get_paginated_response(serializer.data).data res['count'] = qs.count() return res return serializer.data Because Model Audio no have -create field (which is default ordering field of CursorPagination), so I get error: FieldError at /api/v1/audio/XKdw0tyegW/ Cannot resolve keyword 'created' into field. Choices are: timestamp, audio_id, caption, file, id, uid, user, user_id How can I rewrite ordering field of CursorPagination? -
Order of custom menus in Django CMS
In my Django app, I've added a couple of custom menu entries to Django CMSes menu entries, using the register_menu decorator: @menu_pool.register_menu class MyMenu(Menu): def get_nodes(self, request): entries = [] entries.append(NavigationNode('foo', '/bar', 1)) ... return nodes These menu entries are shown before any CMS menus, i. e. the list of menus returned from {% show_menu %} first produces my entries, then the entries created in the CMS. I'd like my apps entries to come after the CMS entries, but I can't seem to find any documentation on how to do that. I was hoping that the ID would somehow affect the ordering, but it doesn't. Someone suggested that menus are created in the order the apps are listed in INSTALLED_APPS, but moving my app to the very bottom didn't change the order, either. -
update model on transaction success payumoney django
views.py: @login_required(login_url='/account/login/') def FellowPay(request): data = {} txnid = get_transaction_id() hash_ = generate_hash_fellow(request, txnid) hash_string = get_hash_string_fellow(request, txnid) # use constants file to store constant values. # use test URL for testing data["action"] = constants.PAYMENT_URL_TEST if request.user.client_profile.subscription=="Member": amounts=Amount.objects.filter(subscription="M2F") amount=amounts[0].amount data["amount"] =amount else: amounts=Amount.objects.filter(subscription="Fellow") amount=amounts[0].amount data["amount"] = amount data["productinfo"] = constants.PAID_FEE_PRODUCT_INFO data["key"] = config.KEY data["txnid"] = txnid data["hash"] = hash_ data["hash_string"] = hash_string data["firstname"] = request.user.username data["email"] = request.user.email data["subscription"]="Free" if (request.user.is_client == True): data["phone"] = request.user.client_profile.mobile_number else: data["phone"] = request.user.trainer_profile.mobile_number data["service_provider"] = constants.SERVICE_PROVIDER data["furl"] = request.build_absolute_uri(reverse("student:payment_failure_fellow")) data["surl"] = request.build_absolute_uri(reverse("student:payment_success_fellow")) data["paidfellow"]=False print("PAID: ", is_paid_fellow) if request.user.client_profile.subscription=="Fellow": data["subscription"]="Fellow" global is_paid_fellow return render(request, "payu_payment_fellow.html", data) @csrf_exempt def payment_success_fellow(request): data = {} user = request.user global is_paid_fellow is_paid_fellow = True ClientProfile.objects.select_for_update(). filter(user=request.user).update(subscription="Fellow") return render(request, 'payu_success.html', data) Im trying to update the Clientprofile model if payment is success ,but this doesnt work for anonymous user.Any ways to implement this in code? Im checking the model fields in the template to check if user has already paid. A solution was to declare a global boolean variable and change this to true in payment_sucess function and update the model in the FellowPay function itself,but the model field is updating only when i refresh the payment_success page -
CSRF verification failed. Request aborted. while login
i am trying to make a superuser in django using python manage.py createsuperuser but when i tried to login in admin pannel its giving me CSRF verification failed. Request aborted. my browser cookies are enable