Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign foreign key with item ID
I am trying to auto assign a value to a foreign key, so that the model is automatically associated with another model. This is done when an entry is made by a form. I get the following error ValueError at /nodiso/createaction/23/ Cannot assign "'23'": "LeadActions.lead" must be a "Leads" instance. This is the two models: class Leads(models.Model): company = models.ManyToManyField(Company) user = models.ManyToManyField(settings.AUTH_USER_MODEL) name = models.CharField(max_length=265) email = models.EmailField(max_length=265) tel = models.IntegerField() dateenq = models.DateField(auto_now_add=True,null=True) def get_absolute_url(self): return reverse('nodisoapp:leadlist') def __str__(self): return self.name class LeadActions(models.Model): lead = models.ForeignKey(Leads) name = models.CharField(max_length=265) crdate = models.DateField(auto_now_add=True) Duedate = models.DateField() creator = models.CharField(max_length=265) overdue = models.IntegerField(null=True,blank=True) def get_absolute_url(self): return reverse('nodisoapp:leadlist') def __str__(self): return self.name This is the View class ActionCreateView(LoginRequiredMixin, generic.CreateView): login_url = '/scrty/login/' template_name = "nodiso/actioncreate.html" form_class = forms.LeadActionCreateForm def form_valid(self, form): self.object = form.save(commit=False) self.object.lead = self.kwargs['pk'] self.object.creator = self.request.user self.object.save() return super(LeadCreateView, self).form_valid(form) This is the model form class LeadActionCreateForm(forms.ModelForm): class Meta: model = models.LeadActions fields = ['name','Duedate'] I would appreciate the help. -
How to assign Django object ownership without explicitly declaring an owner field on all models?
I'm currently trying to figure out per user object permissions for our Django website API. I have several models with sensitive information, that I need to be able to filter on a user basis. For a simplified example of one of the models: Restaurant, main customer of the website. User, each user gets assigned a restaurant when the user account is created. As such, a restaurant can have many users and they all should only be able to access that restaurant's information. Oven, which belong to a specific restaurant. A restaurant can have many ovens. Recipe, which belong to an oven. An oven can have many different recipes. Recipe Results, which belong to a recipe. There can be many different Recipe Results belonging to the same Recipe (different ingredients tried, etc). There are at least 12+ different models. All models from a particular restaurant have to be hidden from other restaurants, we don't want them to be able to look at other restaurant recipes after all! Not all models have a user = models.ForeignKey(User) Without having to go into each one of my models and declaring owner = models.ForeignKey(User), is there a way to filter them in my API List … -
Remove minus sign from number in django tmplate
In my template I have this: {{ gainer.total_progression }} Which produces -5664 I need 5664 I tried {{ gainer.total_progression }}|slice:"1:" but it won't remove the -. What is the proper way to handle this? -
Django ImportError at /graphql
Just can't understand what's wrong at all: Could not import 'ss.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: type object 'Query' has no attribute '_meta'. This is my Query class in application file pages.schema.py: class Query(graphene.AbstractType): user = graphene.relay.Node.Field(UserNode) users = DjangoFilterConnectionField(UserNode, filterset_class=UserFilter) This is my Query class in root file ss.schema.py: class Query(pages.schema.Query, graphene.ObjectType): pass And here are the screenshots of django error with traceback. ]3 Any suggestions how to fix it? -
Django: how to stay DRY using custom querysets with Q object?
In the custom queryset example bellow, the displayable method uses a combination of permanent and scheduled method. It works, but as you can see, I'm repeating myself: class ArticlesByCategoryQuerySet(models.QuerySet): def permanent(self): return self.filter(is_permanent=True) def scheduled(self, service): return self.filter(scheduled_services__in=[service]) def displayable(self, service): complex_query = Q(is_permanent=True) | Q(scheduled_services__in=[service]) return self.filter(complex_query) What is the correct syntax to use Q() and stay DRY? I didn't find such an example in Django documentation. I tried something like that, but it raises a ValueError: too many values to unpack (expected 2): def displayable(self, service): complex_query = Q(self.permanent()) | Q(self.scheduled(service)) return self.filter(complex_query) Thanks for your help. -
django unique model with one to one relashionship
I have 2 models. each of them can have int_number via one-to-one relashionship with IntNumber model. So i need to do IntNumber.number unique for them(user and group should not refer same IntNumber). Extra lines are omitted. class Group(models.Model): int_number = models.OneToOneField( IntNumber, related_name='int_number', on_delete=models.CASCADE, ) class User(AbstractUser): int_number = models.OneToOneField( IntNumber, related_name='int_number', on_delete=models.CASCADE, ) class IntNumber(models.Model): number = models.IntegerField(unique=True) -
Show manytomany field in Django list view
I am trying to show the values of a manytomany field called teachers in a Django ListView. At present my model looks like this: class Classform(models.Model): # Fields name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) # Relationship Fields school = models.ForeignKey('eduly.School', default=1) teachers = models.ManyToManyField('eduly.Teacher', ) My ListView looks like this: class ClassformListView(GroupRequiredMixin, ListView): model = Classform group_required = [u"school_admin"] login_url = "/login/" raise_exception = True And my template for the list view looks like this: <tr> <td>{{object.pk}}</td> <td><a href="{{object.get_absolute_url}}">{{object}}</a></td> <td>{{ object.name }}</td> <td>{{ object.teachers }}</td> <td>{{ object.created }}</td> <td>{{ object.last_updated }}</td> </tr> When this code runs the displayed value for object.teachers is appname.Teacher.None I have noticed that Django has created a table called appname_classform and also a table called 'appname_classform_teachers' but am not sure how I need to change object.teachers to get the name of the teachers. -
Footer doesn't extend to the edge of the screen - not a duplicate
I've seen a few of these on Stack Overflow, but the questions that have been asked don't lead to an answer which solves my issue. Please take the time to look over my code before marking it down or flagging it as a duplicate. I'm working through a book called "Beginning django CMS". I'm finding that a few parts are out of date, and that might be the issue here. It's tough for me to say because I'm new to web design. The footer isn't in a <div>, and I've gone over the padding to see if that helps. Those are the kinds of issues that come up as answers to questions that have previously been posted on Stack Overflow. I'm being left with a footer which begins about an inch in from the left of the screen and seems to be in line with the blog title. Does anyone know what might be causing this? I've checked this in Chrome and Edge so far, both come up with the indent. Here's the HTML: {% load cms_tags staticfiles sekizai_tags menu_tags %} <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv"X-UA-Compatible" Content = "IE=Edge"> <meta name = "viewport" content="width=device-width", initial-scale=1> <link rel="icon" … -
Format Django's server display
For debugging, I add print statement to URL Controller. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] print('urlpatterns: \n', urlpatterns) Server display reads: $ ipython manage.py runserver 8080 Performing system checks... urlpatterns: [<RegexURLResolver <RegexURLPattern list> (admin:admin) ^admin/>, <RegexURLResolver <module 'polls.urls' from '../Documents/Public/Dev/django-tutorial-repo/polls/urls.py'> (None:None) ^polls/>] System check identified no issues (0 silenced). The results I desire is that readable as IPython does in an interactive mode.like, urlpatterns: [<RegexURLResolver <RegexURLPattern list> (admin:admin) ^admin/>, <RegexURLResolver <module 'polls.urls' from '../Documents/Public/Dev/django-tutorial-repo/polls/urls.py'> (None:None) ^polls/>] An IPython automatic format example, In [4]: dir('') Out[4]: ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',] Alternatively, I can edit the print statement one by one. How to set the configuration to enable this function? -
Django Python: Only changed Email Address and now failed to send mail with error
I really dont know what happend. I just changed the Adress of EMAIL_HOST_USER = .. and now i cant send an Email any more. The worst is i tried to revert it but even this doesn't work any more. I really don't get it, i must have changed something without noticing. in my settings.py i have the following: EMAIL_HOST = 'smtp.web.de' EMAIL_HOST_USER = 'myadress@web.de' EMAIL_HOST_PASSWORD = 'mypass' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' and the error appers on this code: send_mail( 'Subject', 'Blah blah blah', 'myadress@web.de', ['to.thisaddress@web.de'], fail_silently=False ) the error which is caused is this: [Errno 10061] Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte Sry its German but it English it means that there is no connection possible to the target-computer By debugging i realized the following: that auth_password and auth_user is None (see in the picture). I Think that could be the problem but i real have no idea how to fix it. I have really checked my address and password a thousand times an it is corret also the problem cant be the email provider web.de i think because both adresse, before and after i changed it, are from … -
Salesforce rate limits: uploading contact details from web app
I have a Python/Django + JS web app that stores user data in a PostgreSQL database. I want to now add a sign-up/subscribe form that uploads the user's contact details to Salesforce and I'm looking for a robust way to do this. I'm confused about the multiple ways to upload to Salesforce and how there are different API limits I have to worry about. It's difficult to estimate how popular the app is going to be and I don't want to lose contact details or have to show a "sorry, try signing up another time" message. Options I've considered: Use web to lead to upload via JavaScript (limit of 500 uploads per day). Use a Python library that uploads each user at the time of submission. Use Heroku Connect to sync the database to Salesforce (looks expensive and you need to ask for a quote). Add all the user data to a database table and run a scheduled job that uploads each row in batches periodically so if I hit rate limits they'll get uploaded eventually. Most complex to implement. -
Define which fields are shown in a Django forms.ModelForm list
I want to restrict which fields are shown in the list view of a Django forms.ModelForm I can restrict which fields are shown in the update and create forms but can't work out how to do this for the list view of the form. My model looks like this: class Teacher(models.Model): name = models.CharField(max_length=255) email = models.CharField(max_length=30) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) My view code looks like this: class TeacherListView(GroupRequiredMixin, ListView): model = Teacher group_required = [u"school_admin"] login_url = "/login/" My form code looks like this: class TeacherForm(forms.ModelForm): class Meta: model = Teacher fields = ['name', 'email' ] I am trying to hide the slug field from the list view. -
How can the foreign field shows the name instead of its id?
In my models.py, there are two model, the AvailableArea has a foreign field refer to AddressRegion: class AddressRegion(models.Model): name = models.CharField(max_length=8) def __str__(self): return self.name def __unicode__(self): return self.name class AvailableArea(models.Model): name = models.CharField(max_length=8) addressregion = models.ForeignKey(AddressRegion, default=1, related_name='availableareas', on_delete=models.CASCADE) def __str__(self): return self.name def __unicode__(self): return self.name In the serializers.py, I serialize all the fields: class AvailableAreaSerializer(ModelSerializer): """ 可用地区 """ class Meta: model = AvailableArea fields = "__all__" In the views.py: class AddressRegionListAPIView(ListAPIView): serializer_class = AddressRegionSerializer permission_classes = [] queryset = AddressRegion.objects.all() The rest framework data is like this: [ { "id": 13, "name": "福州一区", "addressregion": 3 }, { "id": 14, "name": "西南一区", "addressregion": 4 }, { "id": 15, "name": "西南一区", "addressregion": 3 } ] I want the addressregion not shows the addressregion's id, but shows the addressregion's name. -
how to create fieldset in django
I'm new to django. I want to make a formset with 4 forms (name, lastname, phone, address) that I want to have them in 2 groups called: 'general info' and 'optional info'. How can I use fieldset to do that? and how can I parse it? I read some tutorial but none worked. thanks -
Django: Filtering the Distinct Data
I'm trying to build a messaging app. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) This is what I tried in view, data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)) In the template, {% for abc in data %} {{ abc.receiver }}<br /> {% endfor %} How can I print out the distinct users and re-order them based upon new messages as we see on social media platforms? -
Adding a 'view all' endpoint to restful Django
I have this row in my urls.py: url(r'^rss/(?P<rss_id>\d+)/', views.RSSList.as_view()) I want to be able to server also something like http://example.com/rss Which will show the complete rss list. How can I add it while keeping the id option? -
Importing date from HTML into Django views
I'm fairly new to Django and I am facing a bit of a problem. I have my html template in which I have two html date fields - start_date and end_date. I want to pass the contents of those field into my views.py and then display data for that time period, but I am having trouble making it work. Any help will be greatly appreciated. Relevant code: home.html Select time period: <br> From: <input id = "start_date" type="date" name="From" value="{{data.start_date|date:"d/m/Y"}}"> To: <input id = "end_date" type="date" name="To" value="{{data.end_date|date:"d/m/Y"}}"> <input type = "submit"> {% for data in data.all %} {% if data.profile.user.username == user.username %} <tr> <td>{{data.profile.user.username}}</td> <td>{{data.date}}</td> </tr> {% endif %} {% endfor %} views.py import datetime from datetime import date @login_required def home(request): if request.user.is_authenticated(): user = request.user.username start_date = request.GET.get['start_date'] end_date = request.GET.get['end_date'] data = Data.objects.filter(date__range=[start_date, end_date]) context = { 'data': data, 'cpu_hours_all': cpu_hours_all, } models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE def __str__(self): return self.user.username class Data(models.Model): date = models.DateField(blank=True) profile = models.ForeignKey(Profile , on_delete=models.CASCADE) Thanks in advance! -
Django-Registration override Registration Form
I'm using Django-Registration 2.3 for a project and trying to override the standard RegistrationForm with the following: class MyRegistrationForm(RegistrationForm): captcha = NoReCaptchaField() class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2'] widgets = { 'first_name' : forms.TextInput(attrs={'class' : 'form-control'}), 'last_name' : forms.TextInput(attrs={'class' : 'form-control'}), 'username' : forms.HiddenInput(), 'email' : forms.EmailInput(attrs={'class' : 'form-control'}), 'password1' : forms.PasswordInput(attrs={'class' : 'form-control'}), 'password2' : forms.PasswordInput(attrs={'class' : 'form-control'}), } I'm then calling this from my urls.py with url(r'^accounts/register/$', RegistrationView.as_view(form_class=MyRegistrationForm), name='registration_register'), In the template the captcha, first_name and last_name fields are rendered using form-control, the username is hidden but the other fields are rendered without the class. What do I need to do? -
django download images in zip file
I use this code in DJANGO framework to can some user download images. this code work fine and download image every time to press download some user. but this code download absolute images I need to zip this images for any user download. def download_image(request, id): product_image=MyModel.objects.get(pk=id) product_image_url = product_image.upload.url wrapper = FileWrapper(open(settings.MEDIA_ROOT+ product_image_url[6:], 'rb')) content_type = mimetypes.guess_type(product_image_url)[0] response = HttpResponse(wrapper, content_type=content_type) response['Content-Disposition'] = "attachment; filename=%s" % product_image_url return response is easy to change this code to download images in zip file ? -
How can I set up Django Crontab in Docker container?
Let's assume that I would like to run custom management command in Django every day at 12 noon. I have in management/commands file myfile.py and I set it up in this way TIME_ZONE = 'UTC' CRONJOBS = [ ('* 12 * * *', 'django.core.management.call_command', ['myfile']), ] I have added django-crontab to the requirements.txt and 'django_crontab' in INSTALLED_APPS. This file should add data to the PostgreSQL database however it doesn't work. Any ideas why? Maybe I should use Celery scheduler instead? -
Get value of RangeType input field in Django forms?
In my django form I wanted a slider type field. So I used NumberInput widget, code below. from django.forms.widgets import NumberInput class RangeInput(NumberInput): input_type = 'range' class MyForm(ModelForm): .... class Meta: model = Application fields = ['amount', 'reason'] widgets = { 'amount' : RangeInput(attrs={'max': 100000, 'min':10000, 'step':5000}), } Above helped me to get a slider in my form. Pic below. Slider is fine but I want to current value of the slider also to be shown. One way is to manually do using Javascript. Does Django gives a more automatic solution for this? Without showing the value of the slider to the user, the slider is virtually useless. -
Restoring of django database taking more time
For Django database backups and restore. I used this tool https://github.com/django-dbbackup/django-dbbackup. It is taking so much time to restore the database. It is taking 3hours of time to restore a 500MB Compressed file. I used the below command. time python manage.py dbrestore -i django_db_production_backup_20171109_0200.dump.gz -z Is there any alternative methods to reduce the time consumption. -
Different allowed_method for different Authentication in tastypie
I am working with tastypie for my API. I want to create a resource which allows multiple types of Authentications (SessionAuthentication and ApiKeyAuthentication). I want to allow get, post, put, delete methods for SessionAuthentication and just get method for ApiKeyAuthentication. I want to keep the same resource to meet my need. Please help. -
Celery add_periodic_task blocks Django running in uwsgi environment
I have written a module that dynamically adds periodic celery tasks based on a list of dictionaries in the projects settings (imported via django.conf.settings). I do that using a function add_tasks that schedules a function to be called with a specific uuid which is given the settings: def add_tasks(celery): for new_task in settings.NEW_TASKS: celery.add_periodic_task( new_task['interval'], my_task.s(new_task['uuid']), name='My Task %s' % new_task['uuid'], ) Like suggested here I use the on_after_configure.connect signal to call the function in my celery.py: app = Celery('immonaut_backend') @app.on_after_configure.connect def setup_periodic_tasks(celery, **kwargs): from add_tasks_module import add_tasks add_tasks(celery) This setup works fine for both celery beat and celery worker but breaks my setup where I use uwsgi to serve my django application. Uwsgi runs smoothly until the first time when the view code sends a task using celery's .delay() method. At that point it seems like celery is initialized in uwsgi but blocks forever in the above code. If I run this manually from the commandline and then interrupt when it blocks, I get the following (shortened) stack trace: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'tasks' During handling of the above exception, another exception occurred: Traceback (most recent call last): File … -
python social auth partial `NOT NULL constraint failed: social_auth_partial.timestamp` with django
I have following pipelines at settings.py SOCIAL_AUTH_PIPELINE =( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'auth_manager.fb_account_linking.save_number', ) my auth_manager.fb_account_linking.py looks like following: @partial def save_number(strategy, details, user=None, is_new=False, *args, **kwargs): m = MobileNo.objects.filter(user=user) print(len(m)) if not len(m)>0: return redirect('account_kit') I am getting following error: IntegrityError at /auth/oauth/complete/facebook/ NOT NULL constraint failed: social_auth_partial.timestamp Traceback: File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py" in execute 65. return self.cursor.execute(sql, params) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 328. return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: social_auth_partial.timestamp) was the direct cause of the following exception: File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_django\utils.py" in wrapper 50. return func(request, backend, *args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_django\views.py" in complete 28. redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\actions.py" in do_complete 41. user = backend.complete(user=user, *args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\backends\base.py" in complete 40. return self.auth_complete(*args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\utils.py" in wrapper 252. return func(*args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\backends\facebook.py" in auth_complete 110. return self.do_auth(access_token, response, *args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\backends\facebook.py" in do_auth 152. return self.strategy.authenticate(*args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_django\strategy.py" in authenticate 115. …