Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating 2 models using 1 form field in django Modelform
Here are my 2 models : models.py class Item(models.Model): item_category = models.ForeignKey(Category, on_delete="PROTECT") item_name = models.CharField(max_length=100, null=False) item_quantity = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True, editable=False) created_by = models.CharField(max_length=250, editable=False) def ___str__(self): return self.item_name class ItemOut(models.Model): item_name = models.ForeignKey(Item, on_delete='DO_NOTHING') item_quantity = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True, editable=False) created_by = models.ForeignKey(User, on_delete='DO_NOTHING') def __str__(self): return self.item_name Now I've already created a form that creates a new entry into the first model Item, forms.py class AddItemForm(forms.ModelForm): class Meta: model = Item exclude = ('created_by', 'created_at', ) labels = { 'item_category': 'إسم الفئة ', 'item_name': 'إسم الصنف', 'item_quantity': 'الكمية', } views.py def add_item(request): current_user = request.user if request.method == 'POST': new_item = AddItemForm(request.POST, request.FILES) if new_item.is_valid(): item = new_item.save(commit=False) item.created_by = current_user item.save() return redirect('cat') else: new_item = AddItemForm() all_cats = Category.objects.all() cat_count = all_cats.count() item_count = Item.objects.all().count() all_units = Item.objects.aggregate(Sum('item_quantity'))['item_quantity__sum'] context = { 'all_units': all_units, 'item_count': item_count, 'cat_count': cat_count, 'new_item': new_item, 'current_user': current_user, } return render(request, 'townoftech_warehouse/add_item.html', context) Now what I need to do is to create a FORM that creates item_name and item_quanitity in the ItemOut table and take the value from the field that created quantity then subtract it from the original value from Item.item_quanitity where the Item.item_name == ItemOut.item_name -
What is the best way to create like button with django?
I am trying to make social network(small number of users).I have model User and Message so far.I want to create Like and Dislike buttons for Users to like or dislike messages.I could add new model like this class Like(models.Model): user = models.ForeignKey(User) message = models.ForeignKey(Message) created = models.DateTimeField(auto_now_add=True) other option would be to extend the User model.What is the best way to solve this?What are pros and cons? -
models.CharField max_length less in django admin page
I have a model class with following field aliases = models.CharField(max_length=500,default=None,blank=True,null=True) Now, when I try to edit this on Django admin page its maxlength is 20 <input class="vTextField" id="id_alias" maxlength="20" name="alias" type="text" value="ABCD,AAA"> I can't edit it. -
Allowing users to upload profile pictures but 1) form isn't valid 2) not saving correctly
Im trying to allow users to upload profile pictures. Ive done this by creating a File model, and adding a foreign ket referring to a user. A user can upload many files. this is the model: from django.db import models from django.contrib.auth.models import User # Create your models here. class File(models.Model): files = models.FileField(upload_to='images/') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='files') next, the form for the upload looks like this: from django import forms from .models import File class FileForm(forms.ModelForm): class Meta: model=File fields=('files',) widgets={'files':forms.FileInput(attrs={'id':'files','required':True,'multiple':True})} finally, the view 'upload pics' is the following: def upload_pics(request, user_id): if request.method == "POST": form = FileForm(request.POST) if form.is_valid(): pics = form.save(commit=False) pics.user = request.user pics.files = request.Files['files'] pics.save() return redirect(request, 'accounts:profile', user_id) else: form = FileForm() render(request, 'accounts/account_form.html', {'form':form}) return render(request, 'accounts/account_form.html', {'form':form}) i'm running into two issues: 1) the form is not valid, even if I click on several pictures 2) the pictures aren't saving correctly any help would be really appreciated! -
Sentry logs tracker doesn't worked as real-time
I have a django project and set on this raven sentry client for logger handling, and I bring up a sentry server as dockerize. when I tracking logs I need to refresh for logs view and real-time button doesn't work for me. Thanks in advance. -
Celery - importing models in tasks.py
I'm having an issue getting access to models in my tasks.py My goal is to send an email at various parts of the application (user registration, reset password etc..). To do this I pass the user id(s) to a celery task called 'send_email'. @shared_task() def send_email(sender_id=None, receiver_id=None, type=None, message=None): sender = User.objects.get(id=sender_id) receiver = User.objects.get(id=receiver_id) logger.info("Starting send email") Email.send_email(sender, receiver, type, message) logger.info("Finished send email") The task then needs to use the id to retrieve the user and send them an email. This breaks down when trying to import the User model into the tasks.py file. I receive an error raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Things I've tried calling django.setup() at the top of tasks.py file - causes raise RuntimeError("populate() isn't reentrant") causes the same error when put in send_email method as well. These were suggestions on other similar questions in SO Importing model in 'send_email' method, allows the worker to start but causes the following error raise AppRegistryNotReady("Apps aren't loaded yet.") This was another suggestion on a similar question in SO Removing .delay when calling the 'send_email' function which works (with imports at top of tasks.py file or in send_email method) but as the … -
Gmail API: messages KeyError
I've got a function that's connecting to Gmail API and has to show me to whom was the message sent (or from whom did I get it). And so I get the adress from every email and put it into a list "topers" The problem is I can't understand how it should be written correctly. In the documentation is says that I can get it by adding "format" and "metadataHeaders[]" to the parameters. But all this needs a message_id. The problem is I can't understand how it should be written correctly. from apiclient import errors from quickstart import service def GetTop(n): try: if n == 1: label_ids =["INBOX"] else: label_ids = ["SENT"] user_id = 'me' response = service.users().messages().list(userId=user_id, labelIds=label_ids).execute() topers = [] if 'messages' in response: topers.extend(response['messages']) count = 0 while 'nextPageToken' in response: page_token = response['nextPageToken'] response = service.users().messages().list(userId=user_id, labelIds=label_ids, pageToken=page_token,format ="METADATA",metadataHeaders= ["To"] ).execute() topers.extend(response['messages']) print (topers) pass except errors.HttpError as error: print ('An error occurred: %s' % error) I tried by just listing all the messages by label_ids and getting those metadataHeaders from each one (I need to get first all adresses from "INBOX" and then separately from "SENT", I just call the function twice but with different … -
Can't Get AJAX to django
My HTML is like this: $.ajax({ type: "GET", url:"/ajax/validate_supplier/", data:{ 'supplier_name': supplier_name }, dataType: 'json' }); My django url is this one: path('ajax/validate_supplier/', views.validate_supplier, name='validate_supplier'), And my view is this: def validate_supplier(request): supplier_name= request.GET.get('supplier_name',none) data={ 'name_is': supplier_name } return JsonResponse(data) This simple ajax get is not working for me, what am I doing wrong? -
How to simply update an image with new parameter in django
I'm trying to build a website in Django to show the results of my work. I'm completely naive to Django, so please make it as simple as possible. I tried to google solution to this problem, but I cannot even understand much from the tutorials. Let assume I have a function get_image, which returns image (as a HttpResponse) depending on global parameter i. On button click I need to update this global parameter i (e.g. i += 1) and reload image from get_image with updated parameter without reloading the whole page (so jQuery and AJAX will probably help). And also: this global parameter needs to be unique to every user running this page. How can I accomplish this? -
Django + (django-model-utils): Combining two models / inheriting from two models
I recently learned about model inheritance in Django. I used it to great succes using the awesome package django-model-utils. I inherited from the TimeStampedModel and from the SoftDeletableModel. My problem is that I only managed to do the inheritance while inheriting from one model. I now would like to inherit from both models at the same time. Is there a way to inherit from two models or to combine them? How would I best go about doing this? PS: I've tried to combine them myself by putting the SoftDeletableQuerySetMixin in front of the TimeStampedModel in my model that inherits, but it broke things. Also I saw that django-model-utils comes with great tests out of the box and when I would succeed at combining them manually, I think I would have to write new tests for the combined model, wouldn't I? Is there a smart way to combine these models? -
Passing the list from one function to another
i build a project that can do import/export excel file the import is done. now i'm trying to export excel file then the data will not exported. i get the ID into the list and pass to the other function for filter the rows and get the correct data. but when i click to download the list will become empty it doesnt have the ID so that the excel file is download blank. what should i do? Here is the code: def SetUpBoxImport(request): user = User.objects.all() filename = [] filelen = [] not_inserted_num = [] get_inserted_data = [] #get_inserted_data = download_excel_data() row=0 col=0 not_inserted_id = [] worksheet = [] inserted_num = [] activated = [] inserted = 0 not_inserted = 0 ActiveCount = 0 getID = MIT_Dish_Company.objects.all() get = request.POST.get('CompanyID') if request.method == 'POST': gsn = MIT_DISH_ManageSettupBox() SettupBox_resource = ManageSettupBox() dataset = tablib.Dataset() new_SettupBox = request.FILES.get('setupboximport', None) os.chdir("..") files = glob.glob('*.xls') filelen = len(files) if filelen>0: filestring = files[0] workbook = xlrd.open_workbook(filestring) xl_sheet = workbook.sheet_by_index(0) for r in range(1,xl_sheet.nrows): getSl_num = {} SmartNumber = xl_sheet.cell(r,0).value SerialNumber=xl_sheet.cell(r,1).value DeviceStatus=xl_sheet.cell(r,2).value SmartCardType = xl_sheet.cell(r,3).value getcompany = request.POST.get('Company','') for getcom in getcompany: getcomp = MIT_Dish_Company() getcomp.CompanyID=MIT_Dish_Company.objects.get(CompanyID=int(getcom)) try : CheckSl_num = MIT_DISH_ManageSettupBox.objects.get(SerialNumber = SerialNumber,SmartNumber = SmartNumber,CompanyID=int(getcom), … -
Djnago flatpages sitemap generating incorrect urls
In my main urls.py, I have the following: url(r'^pages/', include('django.contrib.flatpages.urls')), I can create flatpages and access them via www.example.com/pages/<url_name_given_via_admin>/ In the same url conf, I also have the following: from django.contrib.flatpages.sitemaps import FlatPageSitemap from django.contrib.sitemaps import views as sitemaps_views sitemaps = { 'flatpages': FlatPageSitemap, } url(r'^sitemap\.xml/$', sitemaps_views.index, {'sitemaps': sitemaps}, name='sitemap'), url(r'^sitemap-(?P<section>.+)\.xml$', sitemaps_views.sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), The problem being, the sitemaps urls generated for flatpages does not append pages/ to the urls, and they look like <loc>http://localhost:8000/about/</loc> instead of <loc>http://localhost:8000/pages/about/</loc> Where am I going wrong? -
notification feature for django project
I'm trying to add notification feature just like social network sites do something like: ( 'x user has add comment', ' x user has like your post' ..) and so on I was searching for a guideline for this feature in django to follow up, I found this answer "How to use django-notification to inform a user when somebody comments on their post " but since it's 6 years ago, some functions is deprecated and webpages links is down. And I believe since 6 years django community add some built-in feature make these things easier. the framework django-notification now become pinax-notifications and as I read it's based on email notification - that not what i'm looking for-. For example let's say my current project has 3 classes in models as following : class user(models.mode): ..... class post(models.mode): user = foreignkey(user) ..... class comment(models.mode): user = foreignkey(user) post = foreignkey(post) ..... class likse(models.mode): user = foreignkey(user) post = foreignkey(post) comment = foreignkey(comment) ..... Is there any guideline for modifying the project to add-on notification feature ? btw, i'm working on django 1.11 and python 3 -
Django - Formset created dynamically not saving
I've created a CreateView form with a Parent (named 'Entrada') model and (multiple) Children models (named 'BalaMateriesPrimeres') as formset. Those formset are created dynamically with a JS I've created so I can add as many children I want (instead of adding one by one with elo80ka dynamic formset plugin). But the problem is that the formset is invalid. When print the formset at the 'def post' method, I get the html tags but the 'value' field of each one is empty. This is the relevant code: forms.py class EntradaForm(ModelForm): class Meta: model = Entrada exclude = () class BalaMateriesPrimeresForm(ModelForm): class Meta: model = BalaMateriesPrimeres fields = ['quilos', 'material', 'cost_unitari'] BalaMateriesPrimeresFormSet = inlineformset_factory(Entrada, BalaMateriesPrimeres, form=BalaMateriesPrimeresForm, can_delete=True, extra=1) views.py class EntradaCreateUpdateView(LoginRequiredMixin, UpdateView): model = Entrada form_class = EntradaForm formset_class = BalaMateriesPrimeresFormSet def get_context_data(self, **kwargs): data = super(EntradaCreateUpdateView, self).get_context_data(**kwargs) if self.request.POST: data['bales_materies_primeres'] = BalaMateriesPrimeresFormSet(self.request.POST) data['materials'] = Material.objects.all() else: data['bales_materies_primeres'] = BalaMateriesPrimeresFormSet() data['materials'] = Material.objects.all() return data def get_object(self): self.creating = 'pk' not in self.kwargs if self.creating: return None # Sucess else: obj = super().get_object() return obj def post(self, request, *args, **kwargs): form = self.get_form() formset = BalaMateriesPrimeresFormSet(request.POST, prefix='bales_materies_primeres') if form.is_valid() and formset.is_valid(): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): … -
How to install python 3.6.5 in python 3.4 virtual environment?
Guys i was recently doing django through a virtual environment and at that time i had python 3.4 installed but now i uninstalled python 3.4 and i installed python 3.6.5 and when i activated my virtual environment and running server on localhost i got a error which said "Python34.dll Not Found!" i think this has to be the virtual environment mistake because python 3.6.5 is successfully added to path. So i think that installing a newer version of python in the virtual environment will work? Thanks, -
Django: Overriding UserAdmin doesn't do anything
Can't figure out why overriding UserAdmin in my project doesn't do anything. The changelist is the same as before. I properly unregistered and registered User model and the application is after auth in settings.py For example, there are all columns in change list, not only id and username. admin.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin # Register your models here. from django.contrib.admin import register from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group, User admin.site.unregister(Group) admin.site.unregister(User) class UserProfileInline(admin.StackedInline): model = MaklerProfile @register(User) class UserCustomAdmin(UserAdmin): fieldsets = ( (None, {'fields': ('username', 'password')}), # (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) ordering = ('username',) inlines = [UserProfileInline] list_display = ['id', 'username',] Do you know where is the problem? -
django-crontab missing hash after a day
I'm using django-crontabto run a function every day in my server. When I add the cron with python manage.py crontab add everything is ok, I can see the crons and they execute normally (I've tested them running every minute and they do what I want). The problem is the next day it always throws this error: RuntimeError: No job with hash bdd84e8eebbbbc48c5d39e0245c78c93 found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue!` I have set the CRONTAB_DJANGO_PROJECT_NAME and CRONTAB_DJANGO_MANAGE_PATH because i have a local manage.py. Seems like it loses the hash somehow from one day to another. This is my settings: CRONJOBS = [ ('0 7 * * 1-5', 'api.cron.email_to_late_docs', '>> {}'.format(BASE_DIR + '/logs/log_{:%d_%m_%Y}.log'.format(time.now()))), ('0 7 * * 1-5', 'api.cron.email_ten_days_before', '>> {}'.format(BASE_DIR + 'logs/log_{:%d_%m_%Y}.log'.format(time.now()))) ] CRONTAB_DJANGO_PROJECT_NAME = 'public_html' CRONTAB_DJANGO_MANAGE_PATH = BASE_DIR + '/manage_local.py' Has someone face this error before? -
Django Rest Framework with JWT Get User Info
I have a Django API that uses JWT for authentication (see this tutorial). Currently it gets the token fine and attached to that is a user_id for React. Example token returned from /api/auth/token/obtain: { "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwidXNlcl9pZCI6MSwiZXhwIjoxNTI1NjgxMjU3LCJqdGkiOiJlZTk4Y2I2ZmI3ZTk0OWVlYmNiNDU4NjA2N2ZmMGYzMyJ9.-8lXUwWivg4vaucDGRj7InqDQrn8WuflvwL1ebNHlFg", "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsInVzZXJfaWQiOjEsImV4cCI6MTUyNTc2NzM1NywianRpIjoiMmM4NDBlZWI3NWE0NDFkMmFiMGQxZjViNDdkYTcyNDgifQ.G70wMPL2OdrDx06HulGdVS3KQvZvNtjKoli1rKYXbxs" } But if I have an endpoint that alters a model created and owned by that user (it has an model field where owner is the pk of the User), how can I compare if that model is owned by the user when using JWT for authentication? When I was using Django views, it was just simply check if the values were the same based off the user from the request, but with JWT the user doesn't seem to actually log in to the Django auth system. -
Django, Wagtail admin: handle many to many with `through`
I have 2 models with a through table such as: class A(models.Model): title = models.CharField(max_length=500) bs = models.ManyToManyField(to='app.B', through='app.AB', blank=True) content_panels = [ FieldPanel('title'), FieldPanel('fields'), # what should go here? ] class AB(models.Model): a = models.ForeignKey(to='app.A') b = models.ForeignKey(to='app.B') position = models.IntegerField() class Meta: unique_together = ['a', 'b'] I'm getting the following error when trying to save: Cannot set values on a ManyToManyField which specifies an intermediary model. That error makes sense to me. I should save AB instances instead. I'm just unsure what's the best way to achieve that in Wagtail. -
Transformation of django dataset
class Package (models.Model): name = models.CharField(max_length=200) class Package_feature (models.Model): category = models.CharField(max_length=200) price = models.DecimalField(max_digits=8, decimal_places=2, default=Decimal('0.00')) package= models.ForeignKey(Package, on_delete=models.CASCADE, null=True) the content of Package is as follows: name set1 set2 set3 set4 set5 the content of Package_feature is as follows: category price package 'network equip ', 5000, set1 'network equip ', 4000, set2 'network equip ', 3000, set3 'computer equip', 2000, set1 'computer equip', 1500, set2 'computer equip', 1000, set3 'accessories', 200, set4 'accessories', 300, set1 'accessories', 500, set2 'others', 300, set5 What I want to produce is a data structure of the following: category set1 set2 set3 set4 set5 'network equip', 5000, 4000, 3000, -, - 'computer equip', 2000, 1500, 1000, -, - 'accessories', 300, 500, -, 500, 300 Can this be done using django query or i have to hand code the result table? -
Filter two models in Django
I am creating a website with Django. I want to filter a model based on the content of another model. What I have so far is this: my_var = ModelOne.objects.filter().order_by() I want to filter it based on this: len(ModelTwo.objects.filter(approved=True)) Does someone have any ideas? -
Django triggering password reset in any view
As a django newby I'm looking for a solution I wasn't able to find yet. I want to trigger password reset a bit different than the OOTB solution and couldn't make it yet. There is a button for admins in my custom admin which should trigger the password reset. I know the email of the user and can pass it to the view but I don't know how should I trigger the password reset. I've found that I could .save() the email to the password reset form but it didn't work for me. I'm using django 2.0 python 3.5.2. Could you give me any suggestions how to make it work? Thanks in advance, Álmos -
Sending Email with Django
I'm trying to send email with django. Here's my settings.py file. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = 'mailpassword' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'mymail@gmail.com' I've also enabled access to less secure apps in the gmail settings. On the production server whenever I try to send an email, it's raising an error in the command line upstream prematurely closed connection while reading response header from upstream. On webpage it's showing 502 Bad Gateway error. How can we solve this issue? Thank You . . . -
Could the Django model set only one row data?
Could the Django model set only one row data? class ExpireDay(models.Model): days = models.IntegerField(unique=True) class Meta: ordering = ['-days'] def __str__(self): return self.days def __unicode__(self): return self.days I have a model like upper, I want the table only have one row data, is it possible to limit that? -
when a database content deletes ,how can i redirect to same page using url argument passing method?
i want to delete a database content.bt after deletion utl goes to http://127.0.0.1:8004/login/delete_detail/6/ ..how can i redirect to success.html ie in the same page class DeleteView(generic.TemplateView): template_name = 'success.html' success_url='/login/success' def get_context_data(self, *args, **kwargs): context = super(DeleteView,self).get_context_data(**kwargs) did = self.kwargs['did'] q_obj = Quest.objects.filter(id=did) q_obj.delete()