Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to call an API from flutter
Every time i call the end point I get an error message. Values Represented are Static for this example but later on these will be replaced by real values, the Goal is to retrieve the values on the database through the Api. the Values, order and entries have be checked for spelling errors. Any insight would be appreciated. class Search { final int id; final String location; final int employer; final String service; final int position; final String userId; Search({this.id, this.location, this.employer, this.service, this.position, this.userId}); factory Search.fromJson(Map<String, dynamic> json) { return Search( id: json['id'], employer: json['employer'], location: json['location'], service: json['service'], position: json['position'], ); } Map<String, String> headers = { 'content-type': 'application/json', 'accept': 'application/json', 'authorization': 'ztNMKpkGM4USORPl45HGEl8EMyh1' }; Map toMap() { var map = new Map<String, dynamic>(); map["employer"] = employer; map["location"] = location; map["service"] = service; map["postion"] = position; return map; } } Future<Search> createSearch( int employer, String location, String service, int position) async { final http.Response response = await http.post( 'http://m-waks/employer/asefsdgcsjdsxxx/search-employees/', headers: { HttpHeaders.authorizationHeader: 'ztNMKpkGM4USORPl45HGEl8EMyh1','Content-Type': 'application/json', 'Accept': 'application/json' }, body: jsonEncode(<String, dynamic>{ 'employer': employer, 'location': location, 'service': service, 'position': position })); if (response.statusCode < 200 || response.statusCode > 400 || json == null) { throw new Exception("Error while fetching data"); } … -
django form autocomplete show data
models.py class Place(CoreModel): name = models.CharField(max_length=255, ) parent = models.ForeignKey('self', null=True, on_delete=models.CASCADE, default=None) place_type = models.CharField(max_length=255, choices=PLACE_TYPES, default=CITY_OR_VILLAGE) objects = PlacesManager() class Meta: unique_together = ('name', 'parent') def __str__(self): return self.name forms.py class PlaceForm(forms.Form): place_from = forms.ModelChoiceField(queryset=Place.objects.cities_villages(), widget=autocomplete.ModelSelect2( url='place-autocomplete', attrs={'data-minimum-input-length': 3, } ), required=False, ) place_to = forms.ModelChoiceField(queryset=Place.objects.cities_villages(), widget=autocomplete.ModelSelect2( url='place-autocomplete', attrs={'data-minimum-input-length': 3, } ), required=False, ) trip_type = forms.CharField(label='Chose trip type', widget=forms.Select(choices=TRIP_TYPES), required=False, ) As you can see in the picture, we have autocomplete with the same name. I would like the form to display the name and parent, how can I do this? -
Django admin site shows Blog object(1) instead of what I typed in
Python version: 3.8.2 Django version: 3.0.4 Here is my model: from django.db import models class Blog(models.Model): """Something the user wants to talk about""" text = models.CharField(max_length=100) date_created = models.DateTimeField(auto_now_add=True) def _str_(self): """Return a string representation of the model.""" return self.text But, in the admin site, it shows me this. (I can't embed images yet...) So, I open Command Prompt, and open the manage.py shell. Then, I type in: from blog_bots.models import Blog Blog.objects.all() and it gives me <QuerySet [<Blog: Blog object (1)>, <Blog: Blog object (2)>]>. But when I do Blog.objects.get(id=1).text, it gives me "Django4Life", which is the test that I did and it is what Blog object(1) is. However, I want it to say what I typed in on the admin site (Django4Life), not Blog object(1). -
ValueError at /post/new/ Cannot assign "<SimpleLazyObject:<User: chetan>>": "Post.author" must be a "User" instance
I keep getting this error "ValueError at /post/new/ Cannot assign ">": "Post.author" must be a "User" instance." class User(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE) def __str__(self): return self.user.username class Post(models.Model): author = models.ForeignKey('User.User',related_name="posts",on_delete = models.CASCADE) text = models.TextField() created_at = models.DateTimeField(default = timezone.now) updated_at = models.DateTimeField(blank = True,null =True) def update(self): updated_at = timezone.now() self.save() def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class CreatePostView(LoginRequiredMixin, CreateView): # form_class = forms.PostForm fields = ['text',] model = Post def form_valid(self, form): self.object = form.save(commit=False) form.instance.author = self.request.user self.object.save() return super().form_valid(form) Please help! -
How to get all fields of tables related through a foreign key as well as a many to many relationship in django ORM?
I have a table User_Device with fields username, num_of_years and device (foreign key), table Device with fields id, name, type and many to many relationship on field property, which is the third table Property that has fields id, name, location. I know how to get all the fields from the first 2 tables: User_Device.objects.select_related('device').all() I also know how to get all the fields of the many to many table: Device.property.through.objects.all() or filter using: Device.property.through.objects.filter(property=12) which gives me all the fields of the many to many table alone, which looks like Device_Property with fields device_id, property_id I have 2 questions: How do I get all fields of the Device table and the property table like the SQL query would give when you inner join it like: select d.*,p.* from device_property dp inner join property p on dp.property_id=p.id inner join device d on dp.device_id=d.id How to inner join all the three tables and get all fields like the result of the query: select ud.*,d.*,p.* from user_device ud inner join device_property dp on ud.device_id = dp.device_id inner join property p on dp.property_id=p.id inner join device d on dp.device_id=d.id In conclusion table A has a foreign key field on table B and table B … -
How to Upload and display the image by using model form in django?
I've been trying to upload and display the image but it doesn't show the image. In models.py class upload(models.Model): Comments = models.CharField(max_length=200) img = models.ImageField(upload_to='images/',blank=True) forms.py class upl(ModelForm): class Meta: model= upload fields= ['Comments','img'] views.py def home(request): form=upl() if request.method=='POST': form = upl(request.POST, request.FILES) if form.is_valid(): Comments = form.cleaned_data['Comments'] img = form.cleaned_data['img'] p=upload(Comments=Comments,img=img) p.save() return render(request,'home.html',{'form':form,'up':upload.objects.all(), }) in template <form method="POST"> {% csrf_token %} {{form.as_p}} <br> <BUTTON TYPE ="SUBMIT">Submit</BUTTON><br> <br> </form> {%for i in up %} {{i.Comments}} <img src ="{{i.img}}", alt=""> {%endfor%} so this is showing comments but not image. I don't know why the image is not showing. PLEASE HELP ME OUT -
Django - How to leave ImageField blank if user doesn't upload image
I'm trying to build a recipe app that allows users to upload images and save recipes in a list. The problem I'm facing is when the user doesn't upload an image, I get error: attribute has no file associated with it. Error I've looked in Django documentation & tried using default tag in my HTML template with no success. The value is named image_ingredients in models.py How could I make it so the user can just leave the ImageField empty? Here is my code: models.py # Recipe Field class Recipe(models.Model): title = models.CharField(max_length=200) # TODO: Add default image if image is left blank image = models.ImageField(upload_to='recipes/images/', blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,) daily_meals = ['Breakfast', 'Brunch', 'Elevenses', 'Lunch', 'Tea', 'Supper', 'Dinner'] meal = models.ForeignKey(Meal, limit_choices_to={'name__in': daily_meals}, on_delete=models.CASCADE,) image_ingredients = models.ImageField(upload_to='recipes/images/', null=True, blank=True) ingredients = models.TextField(blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title views.py # Solo recipe with instructions def solo(request, recipe_id): recipe = get_object_or_404(Recipe, pk=recipe_id) return render(request, 'recipes/solo.html', {'recipe':recipe}) solo.html <h4>Ingredients</h4> <img src="{{ recipe.image_ingredients.url }}"> <p>{{ recipe.ingredients }}</p> -
toggle-btn won't show up next to sidebar
First of all I'm using Django, and I've my CSS inside of my HTML file. Here's what my situation looks like as of right now: I've finished setting a sidebar for the dashboard, aka the members area, and I want to offer users the option to show or hide the latter, just like most popular website nowadays do, including Youtube. I've the following code in the body: <div class="toggle-btn"> <span></span> <span></span> <span></span> </div> And the following one in the head <style type="text/css"> .toggle-btn { position:absolute; left:230px; top:20px; } .toggle-btn span { display:block; width:30px; heigh:5px; background:#151719; margin: 5px 0px; } </style> It is indeed supposed to look just like this , but nothing shows up next to the sidebar. If someone could point out what I might have done wrong, or missed doing, I would super appreciate it. -
Django URL regex between various exact string matches
Django (v2.2) I'm trying to achieve a route which consists of three possibilities all, gs and webservice to do a filter in a table on the page. path(r'^(?P<mode>all|gs|webservice)$', get_orders, name='dash.orders_mode'), path('(?P<mode>/^all$|^gs$|^webservice)/$', get_orders, name='dash.orders_mode'), both ways don't seem to work It's because there are ids on the route aswell. -
How to delete from the form the currency choice in MoneyField
Goodmorning Guys, I'm new in django and I want to ask you the following question. I have in models.py two class: class Single_Income(models.Model): income_label = models.CharField(max_length=100, editable=True) income_jan = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) income_feb= MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) class Total_Income(models.Model): total_jan = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) total_feb= MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) In views I have the following code: def ricavi_dalle_vendite(request): items = Single_Income.objects.all() if request.method == 'POST': form = SingleIncomeModelForm(request.POST) if form.is_valid(): print("Il form è valido") new_input = form.save() else : form = SingleIncomeModelForm() context= { "form": form, 'items': items, } return render(request, "app/income.html", context) So completing the form in the web_application (url "app/income.html") it's possible to fill the Single_Income. Now I want to fill automatically the Total_Income model (after the saving of Single_Income model data) in this way: Single_Income: |____Jan____|___Fab_____| |____100___|_____100____| |____100____|____100____| Total_Income: |____200____|____200____| -
Publishing video to youtube from a django app
I have a Django app which shows youtube videos. Now the user can click share and post the video to FB. Once the video is posted, the user should be able to click on the video and play it within FB page. This functionality is very similar when we add a youtube link in gmail and the receiver upon clicking gets a popup window which plays the video. How can I achieve this? Thanks in advance for your answers. -
How to add a default array of values to ArrayField?
Is it possible to add a default value to ArrayField? I tried to do this for email field, but this did not work: from notifications import constants from django.contrib.postgres.fields import ArrayField class NotificationSetting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='notification_setting') telegram = ArrayField(models.CharField( choices= constants.NOTIFICATION_SOURCE, max_length=30 ), default=list) email = ArrayField(models.CharField( choices= constants.NOTIFICATION_SOURCE, max_length=16 ), default=list(dict(constants.NOTIFICATION_SOURCE).keys())) class Meta: db_table = 'notification_settings' def __str__(self): return f'Notification setting for user {self.user}' And override the save method of the model would be bad practice, I think. -
Django celery beat - can't compare offset-naive and offset-aware datetimes
Im using celery and celery beat to create some tasks, ive added a couple to the DB and when I try and run the below celery -A my app beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler I get the error: 2020-03-20 17:49:03,938: INFO/MainProcess] Writing entries... [2020-03-20 17:49:03,941: CRITICAL/MainProcess] beat raised exception <class 'TypeError'>: TypeError("can't compare offset-naive and offset-aware datetimes") Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/celery/apps/beat.py", line 109, in start_scheduler service.start() File "/usr/local/lib/python3.7/site-packages/celery/beat.py", line 631, in start interval = self.scheduler.tick() File "/usr/local/lib/python3.7/site-packages/celery/beat.py", line 329, in tick self.populate_heap() File "/usr/local/lib/python3.7/site-packages/celery/beat.py", line 303, in populate_heap is_due, next_call_delay = entry.is_due() File "/usr/local/lib/python3.7/site-packages/django_celery_beat/schedulers.py", line 116, in is_due if now < self.model.start_time: TypeError: can't compare offset-naive and offset-aware datetimes looking online it looks as this may be related to timezone settings in my settings file which ive set to, but it hasn't resolved the issues CELERY_TIMEZONE = 'Europe/London' CELERY_ENABLE_UTC = True TIME_ZONE = 'Europe/London' USE_TZ = True versions: celery==4.4.2 django-celery-beat==2.0.0 any ideas? Thanks -
How to edit tags in post using taggit
Good afternoon. I started learning django and met a problem that I can’t solve. I want to edit tags in a post created using taggit, but I don’t understand how to do it Models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) tags = TaggableManager(through=RuTaggedItem, blank=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'text', 'tags') Views.py class EditPostView(View): def get(self, request, pk=None): edit_post = Post.objects.filter(id=pk) form = PostForm(edit_post.values()[0]) return render(request, 'blog/post_edit.html', {'form': form}) def post(self, request, pk=None): form = PostForm(request.POST) if form.is_valid(): post = Post.objects.get(id=pk) # for tag in request.POST.get('tags'): # f.tags.add(tag) if form.has_changed(): for i in form.changed_data: if (form.data[i] != '') and (form.data[i] != None): post.i = form.data[i] post.__setattr__(i, form.data[i]) post.save() return redirect('post_detail', pk=pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) -
Django package import error "Invalid syntax"
openpyxl package import throws "invalid syntax" error in virtualenv while running the django project. While installing the package through requirements.txt file, I'm getting an error for this package in logs as follows This is the version of openpyxl I'm installing openpyxl==3.0.3 I've tried to install the package manually again by doing a pip install openpyxl but this says successfully installed but failed to build openpyxl. Any help with this issue will be appreciated. Thanks in advance. -
Django Populate DateTimeField valudation Error
This is mym models: class Post(models.Model): timestamp = models.DateTimeField() I am trying to populate this field like this: Post.objects.create(timestamp='20-03-20 8:56') and throws me following error: django.core.exceptions.ValidationError: ['“20-03-20 8:56” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Can anyone help me to fix this? -
Model field for implicit many-to-many (many-to-many-to-many) relationship in Django
Let us say in my models for a django app, I have three models, each with many to many relationship (this is a toy example). class User(models.Model): permissions_group = models.ManyToManyField(Group) class Group(models.Model): permissions_area = models.ManyToManyField(Area) class Area(models.Model): #other irrelevant field data... pass I would like to have a field on my User model, that expressed the relationship between users and Areas, which is an implicit many-to-many model (that is to say I don't define additional relations which create additional tables in the database, I use the relationship which goes through groups). I have considered using a custom manager, but that doesn't seem to allow the kind of relationship filtering that one sees with a standard RelatedField manager; I could simply set a decorated property on the class: class User(models.Model): @property permissions_areas(self): return Area.objects.filter(group__in=self.permissions_groups.all()) But that seems clunky, and doesn't use any django conventions. Is there a conventional way to do this in django using Django's tooling (custom managers or similar) which I am missing? -
Django: Annotate two values of the most recent foreign key
I'm actually using python 3.7 and Django 3.0.4. I using in my app models.py like this for a simple system of messages. from torii.models import User class Room(models.Model): users = models.ManyToManyField(User, related_name='conversations', blank=True) name = models.CharField(max_length=100) class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='messages') user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date = models.DateTimeField(auto_now_add=True) So when my user send a message I create a new Message object attached to my Room. I want to query all Room for a given User and annotate the date of the most recent message and the last message in my query. No problem to get the most recent date in my related messages using Max like this: for room in Room.objects.filter(users=user).annotate(last_message_date=Max('messages__date')).order_by('-last_message_date'): print(room.__dict__) {'id': 7, 'name': 'room-7', 'last_message_date': datetime.datetime(2020, 3, 20, 14, 0, 2, 118190, tzinfo=<UTC>)} {'id': 9, 'name': 'room-9', 'last_message_date': datetime.datetime(2020, 3, 8, 15, 19, 52, 343780, tzinfo=<UTC>)} {'id': 8, 'name': 'room-8', 'last_message_date': datetime.datetime(2020, 3, 7, 17, 18, 32, 648093, tzinfo=<UTC>)} But I don't find any way to simply annotate the content of the last message. I have tried Max('messages__content') but in fact, it's order message by alphabetic order and it's always the same who is returned... I tried several subqueries with F and Q … -
How to render a template in django from a different app using Class Based Views?
I'm feeling I shouldn’t be asking thins question because it seems too easy. But I can't find a solution in the django docs or here. I want to render a template in my class based generic ListView, which is in the templates folder of a different app. My folder structure: my_website -app1 -app2 -mywebsite -templates -users -welcome_pages -welcome_user.html -app3 -templates -mytemplate.html -mytemplate2.html -views.py -models.py In my app3 I have a view that looks like this: class VisualizationView(StaffRequiredMixin, ListView): template_name = ???? model = Project def get_context_data(self, **kwargs): print(self.get_template_names()) context = super(VisualizationView, self).get_context_data(**kwargs) context['projects'] = Project.objects.all() return context So I can easily render a template now in template_name which is in my app3 and spit out all my project objects there. But I want to render the context in welcome_user.html. Normally the documentation says I should use appname/templatename but I get a TemplateDoesntExist Exception. I tried passing to template_name: mywebsite/welcome_user.html mywebsite/users/welcome_pages/welcome_user.html welcome_user.html mywebsite/templates/users/welcome_pages/welcome_user.html If I print out self.get_template_names() I only get a list of templates that are within app3. I thought django would automatically be looking in the whole project wherever a template folder is? What am I missing here? Or is this not supposed to work in a CBV? Apologies … -
Correct way to query in many to many (django)
I am trying to get a list of books that have been added by a favorite by a user. I can pull up a list of all favorites from a user myfavorites = Favorite.objects.filter(user=thisUser)" which will return the correct list of 3 favorites by user1 but then when I try to use that list to get a list of the books with "myBooks" : Book.objects.filter(favorites=myfavorites), I instead only get a single object(the first book the user added to favorites). What is the proper way to query this? Is the problem in my views or my models? views.py def books(request): if 'userid' not in request.session: return redirect('/') else: num = request.session['userid'] thisUser = User.objects.get(id=num) myfavorites = Favorite.objects.filter(user=thisUser) context = { "user" : thisUser, "otherBooks" : Book.objects.exclude(favorites=myfavorites), "myBooks" : Book.objects.filter(favorites=myfavorites) } return render (request, 'app1/books.html', context) models.py class User(models.Model): first = models.CharField(max_length=30) last = models.CharField(max_length=30) email = models.CharField(max_length=40) password = models.CharField(max_length=40) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() class Book(models.Model): title = models.CharField(max_length=45) author = models.CharField(max_length=30) desc = models.TextField() user = models.ForeignKey(User, related_name="books") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = BookManager() class Favorite(models.Model): favorite = models.BooleanField() user = models.ForeignKey(User, related_name="favorites") book = models.ForeignKey(Book, related_name="favorites") created_at = models.DateTimeField(auto_now_add=True) updated_at = … -
gunicorn server hangs when calling itself
I have a Django REST Framework service that runs on a gunicorn server. Here is what the config looks like: exec gunicorn \ --pid /web/gunicorn.pid \ --workers 4 \ --threads 8 \ --worker-class gthread \ --name my-api \ --chdir /src/api \ --bind unix:/web/.sock \ --timeout 300 \ --limit-request-line 8190 \ wsgi:application I have two views: def view1(request): # Call DB etc. def view2(request): my_api_python_client.call_view1(request) # Hangs! This results in the requesting hanging indefinitely. I understand that calling one view from another sounds counter-intuitive but it has to be done to leverage caching, async calls etc. What is curious is that when I run it as a Pycharm server, it works perfectly well! Question - Why does my request never get processed? How do I fix it? -
How to print an output in an HTML page multiple times using django framework?
enter image description here As per the code shown in the image, how can we use loops to print 'Result : {{result}}' multiple times? -
django how to return classBasedView from in a function
I am trying to put a condition before the password reset view, so I want to return it from a function based view. from django.contrib.auth import views as auth_views def password_reset(request, *args, **kwargs): if some condition: Do something else: return ( auth_views.PasswordResetView( **{ 'template_name': 'reset-form.html', 'email_template_name': 'reset-email.txt', 'html_email_template_name': 'reset-email.html', 'subject_template_name': 'reset_subject.txt', 'form_class': PasswordResetForm, 'success_url': 'etc...', } ), ) With this code I get 'tuple' object does not support item assignment error. What is wrong here? -
show data in another table dynamically in same page using jquery
enter image description here here i make ajax call and show data in new table without loading the page enter image description here here i want to get data by clicking previous table name by using a href on it. but unfortunately i cannot able to get html id which i written i another ajax function due to this i cannot unable to complete this ajax function call because i was testing weather i can get A href id of another function or not i am beginner in web fieldenter image description here . this is also pic of ajax callenter image description here pic of my website page show new table of modules by clicking on projects name but no i want to show dependencies table by clicking on name of module but i did not know to use how get html selector from previous call -
Get JSON values and populate DB/Model in real time in Django
I made a method to request some json values from a url and after populate my DB/models. def get_json(request): response = requests.get('url') geodata = response.json() for obj in geodata['features']: if ImagemServer.objects.filter(pathServer=obj['attributes']['Path']).exists(): imagemServer_list = ImagemServer.objects.all() return HttpResponse('API IS RUNNING') else: for obj in geodata['features']: imagemServer_list = None imagemServer_list = ImagemServer() imagemServer_list.objectidServer = obj['attributes']['OBJECTID'] imagemServer_list.imagemServer = obj['attributes']['Name'] imagemServer_list.sensorServer = obj['attributes']['TX_SENSOR'] imagemServer_list.anoServer = obj['attributes']['NR_ANO'] imagemServer_list.pathServer = obj['attributes']['Path'] imagemServer_list.save() return HttpResponse('API WAS UPDATED') If I run a the url /json (for example) this method runs and everything works. but here is the points: Everything works well in the first catch only - the DB/Model was populated; If I delete any entry in the DB/Model the intention is to check the json again (every time that I access /json) and populate the DB/Model again, based on the Path (if exists or not, unique values and the condition is to not duplicate the values). But in this case, if I delete any entry nothing happens If I run again. Also if I updated the json from the url (I have access to this) nothing is updated in the DB, older or new values. What I missing here?