Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Different urls to different apps in Django
I have two apps in my Django project folder and I want to each urls.py file to point to a different domain. For example: My first project urls.py file looks like this: urlpatterns = [ path('register/', views.register, name='register'), # path('login/', LoginView.as_view(template_name='Clientes/login.html'), name='login'), path('login/', views.login_view, name='login'), path('', views.login_view, name='login'), path('mail/', views.mail, name='mail'), path('profile/config', views.config_view, name="config"), path('profile/dashboard', views.dashboard_view, name="dashboard"), path('profile/terms', views.TermsView.as_view(), name="terms"), path('profile/distribution', views.DistributionView.as_view(), name="distribution"), # path('', LoginView.as_view(template_name='Clientes/login.html'), name='index'), path('profile/order', views.OrderView.as_view(), name='order'), path('profile/list/<pk>', views.detail_view, name='detail_view'), path('profile/list/', views.ListOperationsView.as_view(), name='list_operations'), path('reset-password/', PasswordResetView.as_view(), name="reset_password"), path('reset-password/done/', PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset-password/confirm/', PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('profile/logout/', views.logout_view, name='logout'), path('profile/', views.ProfileView.as_view(), name='profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I want that application to point to example1.com. My second application urls.py file looks like this: urlpatterns = [ path('atendimento/', views.DataView.as_view(), name='user_view'), path('atendimento/opções', views.redirect_view, name='redirect_view'), path('atendimento/rastreio', views.track_view, name='track_view'), path('atendimento/trocas', views.change_view, name='change_view'), path('atendimento/devolver', views.devolution_view, name='devolution_view'), path('atendimento/contato', views.contact_view, name='contact_view'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT_ATENDIMENTO) And I want this application to point to example2.com. How can I do that? -
Celery + Amazon SQS - Tasks performed twice after the last Daylight Saving Time Change
On the last Sunday I found the tasks performed twice. This has been a problem especially for mass emails sent twice. What is the problem? -
Django-How to do the visit counts?
there is a question that makes me feel annoyed,what i want to do is when i request the detail.html then the views of Post model will add 1 as the visit counts ,how to do it?thanks. blog/models.py class Post(models.Model): views = models.PositiveIntegerField(default=0) blog/views.py def detail(request): return render(request, 'blog/detail.html') -
How to convert this SQL into Django ORM?
I'm having a hard time converting SQL query into Django ORM. The point is to reorder QuerySet of Article objects such that every and only every 4th Article has permanent=True. This is the function: def permanent_by_4(self): SQL = """SELECT id FROM ( SELECT id,row_number + (row_number - 1) / 3 as row_number FROM ( SELECT id,row_number() OVER () FROM articles_article WHERE permanent != True )s UNION SELECT id,4 * row_number() OVER () FROM articles_article WHERE permanent = True ) s ORDER BY row_number""" return Article.objects.raw(SQL) The main problem is to get row_number. I tried F('row_number') which doesn't get row_number. Do you know how to convert it? -
Django: how can I generate revser urls including numbers in the string?
I´m using the following code to generate urls: url(r'^productos/(?P<person_id>\D+)/$', views.ProductoView, name="producto"), It works fine with strings that only have letters (dTape). When I try a string that includes a number (d3Tape) I get a nonreverse error. Any clues? Maybe my regex is not ok but I can´t find the solution. Thanks! -
Celery task_success signal parameters
Using Celery 4.1.0 I'm trying to use Celery signals. When using @task_success I'm trying to read the parameters I'm supposed to get and they're all None. This is the signal: @task_success.connect() def task_succeeded(result, sender=None, task_id=None, task=None, **kwargs): print("result: " + str(result)) print("task_id: " + str(task_id)) print("task: " + str(task)) print("sender: " + str(sender)) print("request_id:" + sender.request.id) The signal does get triggered and I see some printing, but seems like all the parameters' values are None. Any idea why? -
How to match combined headers string using Trigram Similarity in Django : Python
Currently I'm able to match the content of a single header only using, sim = model.objects.annotate( similarity=TrigramSimilarity('tag', model.model.tag), ).filter(similarity__gt=0.1).order_by('-similarity') But I need to match the content of 3 headers like model.object1+" "+model.object2+" "+model.object3. Is there a way to do that or do I need to add one more header and populate the db with combined string. -
502 Proxy Error over HTTPS when a request takes more than one minute
I have a application that runs tests with selenium and I'm using Django as backend and Docker to manage the services. The app run tests over a website, automating some functionalities and checking if there are crashes in some point. When it runs over a non secure connection or locally it works fine, but when we run it in a HTTPS connection, like in production, the view that maked the request breaks after exactily one minute, but the tests keep running in the server. We receive the following error: Proxy Error The proxy server received an invalid response from an upstream server. The proxy server could not handle the request POST /myUrl/. Reason: Error reading from remote server -
Filter on a field with choices
I have this field: operation = models.CharField(max_length=10, choices=OPERATIONS) Having this filter works: class OperationFilter(django_filters.Filter): def filter(self, qs, value): try: qs = qs.filter(operation=value.upper()) except: pass return qs With url: /api/v1/operation/?operation=CREATE But having the default filter (without an extra OperationFilter) fails with: { "operation": [ "Select a valid choice. %(value)s is not one of the available choices." ] } Why is a filter on a field with choices failing? For other, non-choice fields, default filters are working fine: /api/v1/operation/?recipient=recipient-19 -
Why can't I activate my Django virtual environment now?
I had to shut down my computer and so windows generated a new commandline terminal without my django virtual environment. Now I can't activate my django virtual environment anymore When I type the command "activate myDjangoEnv" it no longer takes me to my django virtual environment: enter image description here I already have Miniconda installed and I would think I need to install it again right? -
Django - Notification Migrations InconsistentMigrationHistory
When I try to makemigrations or migrate my Django project to the database I'm getting the following error: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration notifications.0001_initial is applied before its dependency pecus.0001_initial on database 'default'. The solution that works it's to drop the entire database, delete migrations files, "python manage.py makemigrations" and "migrate" again But, I don't think that this is the right way for solving this. In every commit of our project (I'm working in a development team) we have to do this in our local databases so the project can work. We are using a MySQL 5.7 database system. Please, what should I do to try to fix this problem? -
Unable to index related models in haystack and Django
I have 2 models Movie, Director and each director is related to multiple movies in my database the Models are class Movie(models.Model): name = models.CharField(max_length = 100) director=models.ForeignKey(Director,on_delete=models.CASCADE) class Director(models.Model): class Director(models.Model): name=models.CharField(primary_key=True,max_length=20) and i used haystack to index these objects where search_indexes.py file is class MovieIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True,use_template=True,template_name="search/indexes/howdy/search_text.txt") name=indexes.CharField(model_attr='name') director=indexes.MultiValueField(indexed=True, stored=True) def get_model(self): print("in get_model") return Movie def index_queryset(self, using=None): """Used when the entire index for model is updated.""" print("in index_queryset") return self.get_model().objects.all() def prepare_movie(self, object): return [mov.all() for mov in object.movie.all()] and the attributes to be indexed is in search_text.txt file {{ object.name }} {% for mov in object.movie_set.all %} {{ mov.name }} {% endfor %} and if i query sqs=SearchQuerySet().all() only the movie name is indexed not director name. sqs[0].name 'Bahubali' is diplayed. sqs[0].director [None] is displayed whereas i have 'rajamouli' as director in my director table. Something is wrong with joining of related tables. Could Someone please Help. -
How can I fix the following error: 'AttributeError at /registreren/ 'User' object has no attribute 'backend''?
Here are the imports: from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm This is the view I did code for registration: def registreren(request): form = UserCreationForm(request.POST) if form.is_valid(): form.save() There are declared variabeles below.. 'gebruikersnaam' means username, nietGecodeerdeWachtwoord means unhashed password, 'wachtwoord' means password, and 'gebruiker' means user. gebruikersnaam = form.cleaned_data.get('gebruikersnaam') nietGecodeerdeWachtwoord = form.cleaned_data.get('wachtwoord') gebruiker = authenticate(username=gebruikersnaam, password=nietGecodeerdeWachtwoord) login(request, gebruiker) else: form = UserCreationForm() return render(request, 'templates/registreren/registreren.html', {'form': form}) This view returns a rendered template named registreren.html wich means register.html... The code of the template is following: {% include 'home/base.html' %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'login/login.css' %}"> <header> <nav> <a href="">Inloggen</a> </nav> </header> <fieldset style="margin-top: 5%;"> <legend>Registreren</legend> <center> <form id="registrerenForm" method="post"> <label><span id="registrerenFormLabelVoerIn">Voer in:</span><br><br> <span id="registrerenFormLabels">Gebruikersnaam<br>Wachtwoord<br>Herhaling wachtwoord</span></label> {% csrf_token %} {{ form.as_p }} I am getting the following error: 'AttributeError at /registreren/ 'User' object has no attribute 'backend'' when I click on the button below after filling in the fields. It creates the user but takes me to a page with that error. How can I fix this? <button id="registrerenButton" type="submit">Registreren</button> </form> </center> </fieldset> -
Translating url regular expressions into path in django 2.1
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), I've been doing tutorial but in django 2.1 you have to use path, how do I translate to 2.1 django compatibile path function? -
New site based on data from another - the best system architecture?
So here's the thing: I have a website, let's call it Catalogue. It is an advanced product catalogue with a lot of items in it. It works on php based CMS, it wasn't done by me and is fairly complete and complicated system. What is important, it has user authentification system and a lot of users in the database. You can not access most of the products unless you are logged in. I want to have another website and I want to build this one on my own. It will contain some additional data for the products, extended download section and some media too. I want to build it with Django. This other website is going to use Catalogue's database a lot: - it needs to authorize users using their login/pass from the Catalogue - It will need customers data to customize their views. I don't have big experience in building more advanced systems. Could you, experienced programmers tell how would you do that? Specifically, I'm concerned about database: should I only use the original database? And merge all django related stuff in it? Will it affect Catalogue? Is it generally good idea? As I've mentioned I'm going to use … -
QuerySet group by several fields django
I'm trying to do a query and I want to group by several fields. Some of those fields are foreign keys. When I get my query set back, I would like those foreign keys to be objects of their respective models. The only way I have found to group by a queryset is values('model1', 'model2', 'somefield'). When I do this, though, the values I get from those fields are the IDs of those objects. What I'm looking for is an equivalent query set to this: SELECT model1, model2, somefield, sum(something) FROM table WHERE (conditions here) GROUP BY model1, model2, somefield And I would like model1, model2 to actually be model objects instead of just IDs. Any good way to do this? Thanks -
django download multiple file which are bytestream
I have some file which saved in database with byte,how can I download these files by django. I know the zipfile package can zip some files, but the files are exist,I want to know how zip some file's bytestream to a zip -
vue.js webpack and static images (without vuecli and nodejs dev server)
I have a vue.js Single File Component where I'd like to reference an image in an src tag. Something like this : <img class="mr-4" v-if="item.picture_file" v-bind:src="item.picture_file"> <img class="mr-4" v-else src="./idavatar.png"> I've read about webpack file-loader. So I added this in my webpack config file. { test: /\.(png|svg|jpg|gif)$/, use: [ { loader: 'file-loader', options: { emitFile: true, }, } ] } If I put a the image file in my entry directory, it is processed then outputed in the output directory. Like other js files. But then, when inspecting the web page : I do not user vuecli or npm dev server. I use Django and embed the vuejs app in a template. Most examples I read explain it should be outputed in an asset directory, that - i guess - is served via npm dev server. How could I finally serve this file? Maybe, there is a way to embed it in the build? I did play with the emit option, hoping it would be merged withe the main.js in /dist ... but nope. It's just not created on disk. Thanks for reading ! -
bug in django template conditionals
Is this a django bug or am I doing something wrong? I have two problems. When I put a block only when there are no posts, it inserts anyway. When the block is inserted, it renders what is inside the block, in the block that I put, but also renders again as if it were some text in my html, in the same position as the block was inserted The block is added anyway, containing posts or not, but block text is only displayed in html when there are posts. because of a bug in the stack editor, I'm posting the code here too: https://pastebin.com/bTpGSRzN images: https://imgur.com/a/jTEgoKg <div class="container"> {% if posts %} <h2 class="titlep mtop">Posts marcados com <span class="focotxt">{{ tag }}</span></h2> <p><small>{{ posts.paginator.count }} encontrados</small></p> {% include "posts.html" %} {% include "pagination_posts.html" %} {% else %} {% block fclass %} fixed-bottom {% endblock fclass %} <h2 class="titlep mtop">Nenhum post marcado com <span class="focotxt"> {{ tag|truncatechars:20 }}</span></h2> <p><a href="/blog/">Voltar para o Blog</a></p> {% endif %} </div> views.py def tags_search(request, tags): template = 'blog/post_tags.html' tag = tags q_obj = Q() for name in [tag]: # iexact or icontains q_obj |= Q(tags__name__iexact=name) post_list = Post.objects.filter(q_obj) page = request.GET.get('page', 1) paginator = Paginator(post_list, … -
django how to insert data in database ( ForeignKey Field )
Models.py class Table_st(models.Model): number = models.CharField(max_length=255) name = models.CharField(max_length=255) stat = models.CharField(max_length=255) def __str__(self): return self.number class Food_sts(models.Model): food_id = models.CharField(max_length=255) foodname = models.CharField(max_length=255) price = models.CharField(max_length=255) inorder = models.IntegerField() def __str__(self): return self.food_id class Order_st(models.Model): table = models.ForeignKey(Table_st, on_delete=models.CASCADE) foodname = models.ForeignKey(Food_sts, on_delete=models.CASCADE) amount = models.IntegerField() (cmd) python manage.py shell from web_app.models import Table_st, Food_sts, Order_st table1 = Table_st.objects.get(number='1') food1 = Food_sts.objects.get(food_id='1') order1 = Order_st(Table=table1, foodname=food1, amount=1) Traceback (most recent call last): File "", line 1, in File "C:\Users\Tanadon\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 485, in init raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) TypeError: 'Table' is an invalid keyword argument for this function -
customising django user model is failing
**Hi I am trying to customize the django default user. Applying migrations works fine. However I get an error when i try to create a super user. Can you please advise why I get this error? ******************** self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/home/gravityns/PycharmProjects/dev/shop/models.py", line 54, in create_superuser user.is_staff = True AttributeError: can't set attribute # accounts.models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django.core.validators import RegexValidator class UserManager(BaseUserManager): def create_user(self, username, password, email): """ Creates and saves a User with the given email and password. """ if not username: raise ValueError('Users must have a username') if not email: raise ValueError('Users must have an email address') user = self.model( username = username, email = self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, username, password, email): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( username, email, password, ) user.is_staff = True user.save(using=self._db) return user def create_superuser(self, username, password, email): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( username, email, password ) user.is_staff = True user.is_admin = True user.save(using=self._db) return user USERNAME_REGEX = '^[a-zA-Z0-9.@+-]*$' class User(AbstractBaseUser): username = models.CharField(max_length=255, validators=[ RegexValidator(regex= USERNAME_REGEX, message = … -
ModelViewSet - Return object by id
I know this might sound like a stupid question but I managed to confuse myself. I have a ModelViewSet class which I would like to return a queryset given a look_up field. For example, hitting /folders/1379e4593-c9d9-4672-a305-7f1707565a0d/ would return just the folder with the specific id. I have tried the following: class FolderViewSet(viewsets.ModelViewSet): authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = FolderSerializer lookup_field = "id" def get_queryset(self): try: id = self.kwargs['id'] print(id) folders = get_folders_by_id(id) return folders except: folders = get_folders(self.request.user) return folders and in my urls router.register(r'folders', FolderViewSet, 'Folder') The problem is that i get: { "detail": "Not found." } even though the id is printed in the console, so it reaches the method. Any idea what might be wrong here? -
Django - How can I join a proxy model with another model
I explain my scenario: I have a PurchaseProxy with a calculated field 'get_income()' and the model Purchase has different fields including one field 'date_purchase'. In addition, I have another Model, Outcome with the fields: 'date','amount' and 'description'. Now, I would an output queryset like this: || Date || Income || Outcome || How can I join the Outcome table with the proxy models (which contains get_income) without a foreign key? Thanks -
Multi-valued field in Django
I can't believe this hasn't come up before but: If I want my model to have one "primitive" field with multiple values, how would I go about declaring it? For example, multiple integers, strings, booleans or datetimes. My initial thought would be to create a second model with my model's FK and one of the fields I mentioned: class MyModel(models.Model): pass class MyModelInteger(models.Model): integer = models.ForeignKey(MyModel) value = models.IntegerField() But (i) does this justify the use of a second table? (ii) How would I access the integer values directly from MyModel? I can't use the through option because that works for intermediate associated models, not with simple attributes. I am probably overthinking this, but surprisingly enough I haven't come across this scenario as far as I memory goes, so I'd appreciate some help to clear it out. -
Android App Sign-Up: How can I let the user sign-up with his Play Store ID?
I am working on a student assignment right now for an application with user management. My professor, who is not an expert on app development but is interested in business models and user experience, said that a normal username-password scheme or social login (OAuth) over Facebook is always more cumbersome than when you enter the app and you are automatically logged in with your Apple-ID/PlayStore ID. I don't have much experience with apps. I am the backend developer and I am using Django (Rest Framework) for the server-side. I couldn't find ANYTHING that helped me with this problem and I want to be sure that there is no way to do this before I tell my professor. Do you guys know anything? Thank you!