Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reducing m-to-n relationship (between object and integer per user) to n-to-1 relationship in Django?
I have a very simple model: class A(models.Model): title = models.CharField(max_length=200) class B(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) a = models.ForeignKey(A, on_delete=models.CASCADE) level = models.IntegerField(default=0) Semantically, I have objects of Type A and use class B to associate an Integer to A per user. I wanted to show a list of all As and show the associated Bs for a user. Unfortunately this turned out to be harder than I expected: During a template, I can ask for the relation from A, but it will return all Bs, as I can not filter for users. During the view, I can not easily combine the two (as I could in an left outer join or similar). I thought of zipping the lists, but doing so would require creating/looking up single instances for each A, e.g.: A_list = [(_,B.objects.get_or_create(...)) for _ in A_list] Which just seems terrible. So my questions are: What is the canonical way to represent such a relationship of user data? If my representation makes sense, how to resolve the problem of associating the data? As I am just a beginner in Django, I just feel like I am missing something, as having user associated data seems like a default … -
Why django hashers are using assert?
I have a question regarding Django implementation of hashers. All of them implement verify method and are doing assert algorithm == self.algorithm. I know that assertions can be disabled through passing the flag -O to the python interpreter on production code. For example, BCryptSHA256PasswordHasher implements verify like that: def verify(self, password, encoded): algorithm, salt, hash = encoded.split('$', 2) assert algorithm == self.algorithm encoded_2 = self.encode(password, salt) return constant_time_compare(encoded, encoded_2) Is assert statement is meant to be used only during the development phase? or there are other reasons? -
Extending custom template tags to other templates in Django
I am using {% load subdomainurls %} in a project where content is dependent on a subdomain (company.example.com). These custom tags include "url" which takes a subdomain argument, {% url 'namespace:name' subdomain='company' %}. I am trying to load these custom tags in base.html so that I do not have to load them in every template. base.html **{% load subdomainurls %}** <!DOCTYPE html> <html lang = "en"> ---snip--- <body> <h1><a href="{% url 'orgs:home' subdomain=request.subdomain %}">App Title</a></h1> {% block content %}{% endblock content %} </body> </html> However, when I then extend base.html, I do not get the custom url tag, but rather the default. login_page.html {% extends 'orgs/base.html' %} {% block content %} <h3>Login a subdomain user:</h3> <form action="**{% url 'users:loginpage' subdomain=request.subdomain %}**" method = 'post'> {% csrf_token %} <table> {{form.as_table}} </table> <button name="submit">Login</button> </form> {% endblock content %} This produces an error from url trying to pass an argument to the url_conf that does not match any patterns. In order to get the template url to function properly, I have to include {% load subdomainurls %} in each template. I've tried loading the custom tags between the body tags and between {% block content %} {% endblock content %} in base.html, … -
Celery worker exit with shell
i use Celery with Django on a Debian server. I connect to the server with putty via ssh and start the celery worker with the following command celery -A django-project worker Now i would like to close putty but than the celery worker exit apparently. Why and what can i do to always run the celery worker? -
How can I ban a package from being added to Pipenv.lock and installed by Pipenv?
There are two packages which provide a module named jsonfield: django-jsonfield jsonfield Unfortunately, we have dependencies which depend on both and the two packages, while interchangable, store data to the database differently. This leads to weird and hard to catch bugs. Also, unfortunately, Pipenv doesn't have any deterministic order of operations when installing dependencies. Sometimes django-jsonfield is installed and sometimes jsonfield is installed. This means that sometimes, randomly, our application breaks because jsonfield is installed instead of django-jsonfield. Is there a way that I can ban django-jsonfield from being added to Pipenv.lock so that only jsonfield will be installed? -
How to pass data comming from database to templates dynamically (at run time /real time )
i have create one Django app in which i want to pass data to html template which is comming from my database (table's last entered user name ) and show it html page but user name can automatically change to new one without refreshing page -
Can't get max value of a field in Django Rest framework
I am trying to build a web app with DRF. I am trying to pass the customer id and display the maximum transaction he has done. This is my views.py class max_val(APIView): def post(self, request, *args, **kwargs): cid = json.loads(request.body).get('cid') queryset = model_name.objects.filter(customer_id=cid).aggregate(Max('transaction')) serialize = serializer_name(queryset, many=True) return Response(serialize.data, status=status.HTTP_200_OK) When I run this I get - HTTP 200 OK Allow: POST, OPTIONS Content-Type: application/json Vary: Accept [ { "cid": null, "transaction": null } ] It is not returning the maximum value. How can I do that ? -
achieve to intended query set in django by ORM
I have below models: class Post(models.Model): title = models.CharField( max_length=100, blank=True, ) description = models.CharField( max_length=1500, ) writer = models.ForeignKey( User, related_name='written_posts', related_query_name='written_post', null=True, on_delete=models.SET_NULL ) klass = models.ForeignKey( 'klass.Class', related_name='posts', related_query_name='published_post', on_delete=models.CASCADE ) users = models.ManyToManyField( User, through='PostUser', related_name="posts", through_fields=('post', 'user'), blank=True, ) class PostUser(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') student = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='student') and now i want get list of posts that are belong to classes id=1 or id=2 and then have PostUser with user_id=3 and student_id=4. i try : Post.objects.filter(klass_id__in=[1,2], users__user__in=[3], users__student__in=[4]).order_by('-create_date').distinct() and another try: qs = PostUser.objects.filter(post__klass_id__in=child.joined_classes_list, user_id=3, student_id=4).order_by('-id').distinct() result = [obj.post for obj in qs] but i can't achieve to goal and result is wrong,but without any error.thank you -
Django Python loaddata fails with django.db.utils.IntegrityError
Took over a database project and I am struggling to load the remote database into the local database. The app was built with django and the local database still relies on sqlite that comes with out of the box. The remote database is of postgresql type unfortunately and illogically. The code I am trying to run in the terminal: python manage.py loaddata *[path to backup.json file]* I get some integrity error so like any reasonable man I flushed the local db because since I want to anyhows load the remote data. python manage.py flush python manage.py syncdata Now when I try to load the data from the json file I get the following error: django.db.utils.IntegrityError: Problem installing fixture 'C:...\lit\backups\dbbackup_20190915_145546.json': Could not load contenttypes.ContentType(pk=1): UNIQUE constraint failed: django_content_type.app_label, django_conten t_type.model Changing the settings.py file from: `DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }` to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'lit', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432' } just gives me a new error. django.db.utils.IntegrityError: Problem installing fixture 'C:..\lit\backups\dbbackup_20190915_145546.json': Could not load contenttypes.ContentType(pk=17): duplicate key value violates unique constraint "django_content_type_a pp_label_model_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(admin, logentry) already exists. I already ran python manage.py … -
Model Validation on InlineAdmin in Django
Within an app for an online shop I have two simple models for products and deliveries: class Product(model.models): delivery = models.ForeignKey(Delivery, on_delete=models.CASCADE) class Delivery(model.models): published = models.Datefield() I am using the build-in Django admin. class ProductInline(admin.TabularInline): model = Product @admin.register(Delivery) class DeliveryAdmin(admin.ModelAdmin): inlines = [ProductInline,] To increase robustness of the app it is very important, that products can't be changed as soon as the related delivery has been published to the customer. So on very attempt to change a product, I need to do some validation to check if the Delivery has been published. Things I have tried: Create fieldset for InlineAdmin with custom clean()method Custom clean() method on the model instance These approaches don't work, though. When implemented, I loose the ability to edit the entire delivery model from the admin panel (I am trying to only limit edits of products). This is because clicking the save Button in the admin Panel will automatically call save() and clean() on the products regardless of weather or not the products were changed. Has someone encountered a similar problem before? -
AttributeError: 'TestPoll' object has no attribute 'factory', django rest framework, tests
I'm currently working through the django api book to learn django rest framework in a virtualenv. I'm using python=3.6, django=2.2.5 and djangorestframework=3.10.3. I'm on the Testing and Continous Integration chapter which is chapter-8. I'm trying to write the first test on there that is: from rest_framework.test import APITestCase from rest_framework.test import APIRequestFactory from polls import apiviews # Create your tests here. class TestPoll(APITestCase): def setup(self): self.factory = APIRequestFactory() self.view = apiviews.PollViewSet.as_view({'get': 'list'}) self.uri = '/polls/' def test_list(self): request = self.factory.get(self.uri) response = self.view(request) self.assertEqual(response.status_code, 200, 'Expected Response Code 200, received {0} instead'.format(response.status_code)) but whenever I run it using python manage.py test it returns with the following error: Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_list (polls.tests.TestPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/vscodeworkspace/official_django/polls/polls/tests.py", line 17, in test_list request = self.factory.get(self.uri) AttributeError: 'TestPoll' object has no attribute 'factory' ---------------------------------------------------------------------- Ran 1 test in 0.006s FAILED (errors=1) Destroying test database for alias 'default'... I can clearly see the factory attribute and how it's called/accessed. I've tried to access the request and response`` attributes usingself``` but that has no effect, So what is the problem? -
Calling a view function with AJAX not working when current path has sub directory or url parameter (Django)
I am using AJAX to call a view function when my pages load to return a count value (no. of items in basket). This works fine for most of my url paths but when the current path has a sub directory or url parameter value I get a 404 error. Below are a some of my url patterns. The bottom one is the view function I call to return the count value. When I visit the 'orders' path the basket count is returned successfully but for the 'order_history' and 'view_order' paths I get the 404, e.g. 'Not Found: /view_order/basket_count' path("my_orders", views.orders, name="orders"), path("my_orders/history", views.order_history, name="order_history"), path("view_order/<int:id>", views.view_order, name="view_order"), path("basket_count", views.basket_count, name="basket_count"), Very new to Python/Django so I'm sure I'm not grasping something very fundamental here and the url patterns are not resolving correctly. I previously had the basket_count in another file called utils.py and referenced it with utils.basket_count which gives the same outcome. I suppose I could just call the function within each of my views but my intention here was to experiment with AJAX. Is there a simple change to my url patterns that will fix this issue with my current setup or is it simply bad practice? -
In Django, can you create a permission that is not based on a model?
I tried creating a permissions with: Permission.objects.create( codename='my_domains.delete_domain', name='Can Delete domains', ) I get this error: django.db.utils.IntegrityError: NOT NULL constraint failed: auth_permission.content_type_id It looks as though content_type is a required field. I do not a model in my app as the app calls an external service. How can I still add this customer permission, without a linked model? -
Why use flywaydb in django?
I am developing a django project. Recently, the project manager and devops decided to switch from django migrations to flywaydb (https://flywaydb.org/). This is explained by the fact that flyway has migration in one place and versioning. I looked at the flyway, but I did not see any conceptual difference with the django migrations. The same approach, only on pure sql. Plus, we lose the additional features of django migrations (auto-generation of migrations, etc.) Can someone explain what is the advantage of flyway? I did not find any good articles. -
Django: Cannot delete broken PolymorphicModel instance
I have this model setup in a Django project (hosted on Heroku) where I am using django-polymorphic: class Product(PolymorphicModel): ... class Book(Product): ... The problem is, that I have managed to create a corrupted instance of both a Product and a Book. This happened when I had an instance of Product which I wanted to convert to an instance of Book and in a moment of insanity did a stupid thing like this: > p <Product: SomeTitle> > b = Book() > b.__dict__ = p.__dict__ > b.save() Now, I know this was idiotic and it threw all kinds of errors. My problem is, that now I am stuck with an instance p which I cannot delete. When calling p.delete() I get the following error: TypeError Traceback (most recent call last) <ipython-input-3-6a6f0dca8e5f> in <module>() ----> 1 p.delete() ~/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py in delete(self, using, keep_parents) 971 972 collector = Collector(using=using) --> 973 collector.collect([self], keep_parents=keep_parents) 974 return collector.delete() 975 ~/.heroku/python/lib/python3.6/site-packages/django/db/models/deletion.py in collect(self, objs, source, nullable, collect_related, source_attr, reverse_dependency, keep_parents) 220 if self.can_fast_delete(sub_objs, from_field=field): 221 self.fast_deletes.append(sub_objs) --> 222 elif sub_objs: 223 field.remote_field.on_delete(self, field, sub_objs, self.using) 224 for field in model._meta.private_fields: ~/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py in __bool__(self) 252 253 def __bool__(self): --> 254 self._fetch_all() 255 return bool(self._result_cache) 256 ~/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py in … -
Configuring HTTPS proxy in anaconda
Hello guys I have created an app using anaconda and django. How can I run my app on https. Is it possible to create a proxy ? -
How does Django models interact with non-Django files
I am new to Django and am learning by doing. My original web app only used a view.py,base.html and another non-Django python file es.py to connect to a NoSQL database(Elasticsearch) to search over index B. I do most of the front-end in base.html. The app now need to have some dependent drop down based on fields in index A and then enable search over index B filtered by the selected value. So the values need to be somewhat "global". I was trying to create select/drop down but it seems Django does not support them in .html. I searched and found it seems that I have to use models.py. I read some examples and can't find how models.py interact with non-Django python files. Is there an example that illustrates this? What's the easiest way to enable the structure for the project? Thanks. -
my Database is not showing on admin panel
models.py from django.db import models class complain(models.Model): name = models.CharField('Name', max_length=120) Email = models.CharField(max_length=120) message = models.CharField(max_length = 600) def __str__(self): return self.name views.py def contact(request): if request.method == 'GET': form = ComplainForm() else: form = ComplainForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['Email'] message = form.cleaned_data['message'] try: send_mail(name, message, email, ['ankushbanik123@gmail.com']) # change this to your email except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('/success') return render(request, "tem/home.html", {'form': form}) """You need a success view for when the form has been submitted. This will render the thank you message once the user has submitted the form. Then on the urls.py, import successView then add path('success', successView, name='success'),""" def successView(request): return render(request, "tem/success.html") form.py class ComplainForm(forms.ModelForm): class Meta: model = complain fields = ['name', 'Email', 'message',] def clean_email(self): email = self.cleaned_data.get('email') return email admin.py from django.contrib import admin Register your models here. from .models import complain admin.site.register(complain) class complainAdmin(admin.ModelAdmin): list_display = ('name', 'Email', 'message') admin.site.register(complain, complainAdmin) -
AWS returns error when generating prepopulated pdf file
I am prepopulating pdf fields with fields from an online form using fdfgen. Locally it works perfectly. It sends an email with the new pdf generated. When deploying to AWS it throws an error AttributeError: 'str' object has no attribute 'status_code' -
How can i add my django project as chrome extension?
I developed a text editor for Bengali language using django framework. Now i want to add my project in chrome extension. I didn't get any proper guidance how can it will be added in chrome extension. -
Overriding js file for FilteredSelectMultiple widget
I am sorry if this a basic question, but I am new to django and could not find any new info about it. I have implemented FilteredSelectMultiple widget to my user form. Now I would like to make some minor changes to widget itself (make translations, edit tooltips etc.). To do so, I copied and edited original js file. Now I would like to override original file with edited one. For this file I created js directory in static. But then I am trying to add it in my Media class loaded widget remains unchanged. How should I do it correctly? My code in forms.url class DrgSkaiciuokle(forms.Form): bazine_kaina = forms.DecimalField(max_digits=5, decimal_places=2, required=True, label="Bazinė kaina", initial= BazineKaina.objects.get(), def clean_bazine_kaina(self): bazine_kaina = self.cleaned_data['bazine_kaina'] return bazine_kaina drg_pasirinkimas = forms.ModelMultipleChoiceField(queryset=DRGkodas.objects.all(), label="Pasirinkite atvejį sudarančius DRG", widget=FilteredSelectMultiple("DRG kodai", is_stacked=False), required=True) class Media: css = { 'all': ('/static/css/widgets.css',), } js = ( '/static/js/SelectFilter2.js', ) def clean_drg_pasirinkimas(self): drg_pasirinkimas = self.cleaned_data['drg_pasirinkimas'] return drg_pasirinkimas -
django internationalization error with msgmerge
PS C:\Users\Ultrathon\Documents\WorkSpace\Edu_Dr_Dayang\venv_Dayang\3IN> python .\manage.py makemessages --l en processing locale en CommandError: errors happened while running msgmerge msgmerge: unrecognized option --previous' Try(null) --help' for more information. -
Show the result of execution Celery task through api by
I get several website addresses in turn from POST request. I will get the job ID. The task collects the number of any HTML-tags. Next, through api, y ou need to display the result by the task number. How to implement saving results from tasks? I will use this code to count HTML-tags(): @app.task(serializer='json') def demo(request, some_url): if request.method=="POST" page = requests.get(some_url) tree = html.fromstring(page.content) all_elms = tree.cssselect('*') all_tags = [x.tag for x in all_elms] c = Counter(all_tags) """for e in c: #print('{}: {}'.format(e, c[e]))""" return с P.S Code is optional, I have enough links on my topic or ideas! -
Django mail sends sensitive information
Django email sends my settings.py file information to the recipient list. i am tried AdminEmailHandler 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } 'app': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, -
Exclude models based on a value from another model with no foreign key
I have the following schema class Review(models.Model): comment_id = models.CharField(max_length=32) class Comment(models.Model): comment_id = models.CharField(max_enght=32) uploaded = models.DateTimeField() NOTE 1 there is no Foreign Key beside the fact that Review and Comment models have exactly the same comment_id NOTE 2 there is one-one/unique relation (only one occurrence of the comment_id will exists at each table) I want to make a select query to fetch all the Review models that their relative Comment model IS NOT OLDER than 10 days.