Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot resolve keyword 'field_object' into field
I have a field object that I want to do filtering with Since the filter field will change dynamically. only_user=User.objects.first() field_object = only_user._meta.get_field(field) QuerySet = User.objects.filter(field_object="xxx") But I couldn't do it, it said Cannot resolve keyword 'field_object' into field. Choices are: ..... -
Creating and receiving model objects
In the admin area, I can create an object of class User, while selecting the project and filling in the user field. Now I have a base.html form, where there is a user field, and the project field is not, because I am on the page of a certain project with a unique id (for example: the form is on the / project / 1 / page (id = 1)). The question is how to create an object of the User class from a form so that it automatically appears in the admin panel. I managed to do this if you ignore the project (ForeignKey). Tell me what to add? base.html <form action="" method="post"> <textarea name="name"></textarea> <button type="submit">Send</button> </form> models.py class User(models.Model): project = models.ForeignKey(Project) user = HTMLField(blank=True, null=True) views.py def index(request): user = Project.objects.all() return render(request, "base.html", {"user": user}) def retro(request): a = User.objects.all() return render(request, "create.html", {"a": a}) def create(request): if request.method == "POST": tom = User() tom.name = request.POST.get("name") tom.save() return redirect('/') else: form = UserForm() return render(request, 'save.html', {'form': form}) In the admin there is a field project, i.e. drop-down list in which we can choose. Each project has its own id. When I am on … -
Not getting model form values in template
Django user profile model form data is not getting displayed on the template, not even giving me an error! I am learning to create Django registration form with user profile models I have created the registration form and profile form successfully but I am not getting any values from models.py file. Models.py class ExtenduserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) age = models.IntegerField() def __str__(self): return self.user.username @receiver(post_save,sender=User) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = ExtenduserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) forms.py class userprofile(forms.ModelForm): birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD') class Meta: model = ExtenduserProfile fields = ('age','birth_date') views.py @login_required() def UserProfile(request,pk=None): profile = ExtenduserProfile.objects.all() return render(request,'dashboard/profile.html',{'profile':profile}) @login_required() def HomeScreen(request): if request.user.is_authenticated: username = request.user.username else : username = 'not logged in' context = {'username':username,'user':user} return render(request,'dashboard/Home.html',context) def singup(request): if request.method == 'POST': form = SignupForm(request.POST) user_profile = userprofile(request.POST) if form.is_valid() and user_profile.is_valid(): user = form.save() profile = user_profile.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username = username, password = password) login(request,user) return redirect(login_view) else: form = SignupForm() user_profile = userprofile() context = {'form':form, 'user_profile':user_profile } return render(request,'account/signup.html',context) HTML file {% extends 'dashboard/base.html' %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Profile</title> </head> {% block content%} <body> … -
Not able to access ForeignKey object using primary key
I am having two models Patient and Ipd, Patient can have multiple Ipd. I am trying to get Patient Info in IpdForm but don't know where I am getting wrong, I am having two models Patient and Ipd, Patient can have multiple Ipd. I am trying to get Patient Info in IpdForm but don't know where I am getting wrong I have already tried qs = Ipd.objects.get(patient__id=patient_id) qs = Ipd.objects.filter(patient__id=patient_id) qs = Ipd.objects.filter(patient_id=patient_id) but nothing worked models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); patient_id = models.AutoField(primary_key=True); gender= models.CharField(choices=GENDER, max_length=10) consultant = models.CharField(choices=CONSULTANT, max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient, on_delete=models.CASCADE, blank=False) def __str__(self): return self.patient.name forms.py : class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','patient_id','consultant','gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient', 'reason_admission', 'presenting_complaints', 'rooms', 'date_of_admission'] views.py: @login_required def ipd(request, patient_id): object = Ipd.objects.filter(patient__patient_id=patient_id) if request.method == "POST": formtwo = IpdForm(request.POST) if formtwo.is_valid(): instance = formtwo.save(commit=False) instance.save() else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'object': object, 'form2': formtwo}) urls.py : urlpatterns = [ url(r'^admin/', admin.site.urls), … -
Multi parameter method in django viewset router
May i know how to setup method with multiparameter like=> @action(methods=['get'], detail=True) def byshiftid(self, request,shiftid): print("Hello World") query = self.get_queryset().get(shiftid=shiftid) serializer = ShiftSummarySerializer(query,many=True) return Response(serializer.data) this shiftid is the parameter. Here is my router=> router.register('shifts_mas', ShiftViewSet, base_name='shifts') Normally my url will be like => api/shift_mas/ Now i would like to do like => api/shift_mas/byshiftid/?shiftid="shift1" something like that. I try like that => @action(methods=['get'], detail=True,url_path='/(?P<shiftid>)') def byshiftid(self, request,shiftid): print("Hello World") query = self.get_queryset().get(shiftid=shiftid) serializer = ShiftSummarySerializer(query,many=True) return Response(serializer.data) But its always say 404 not found. My requirement is to select the record by shiftid.So how can I setup the route like that? -
After receiving the signal how to render it out into template? *DJANGO*
I'm having a hard time rending out into template? after receiving the signal. like how to render the "hehe" into the page or html file i want. @receiver(post_save, sender=Person) def my_callback(sender, **kwargs): print("hehes") -
How to customize login form design?
I want to customize and create my own design on my login form but i don't know how to call the login form i use the form inside the admin. How can i remove the username: & password: and put it inside the text box ? i don't know how to start. Login.html <div class="container"> <form method="post"> {% block content %} {% csrf_token %} {{ form.as_p }} <button type="submit" name="button">Login</button> {% endblock %} </form> </div> {% endblock %} my output Username: {text box} Password: {text box} login button what i want is {text box "Username" "username_icon"} {text box "Password" "password_icon"} button login -
How to convert OrderedDict to Json
I am getting an OrderedDict from an API text in Django-Rest-Framework, how do i convert it into valid json? response = self.client.get(self.api_path + '/stuff.json') gives me [OrderedDict([('title', u'TestTitle'), ('items', [OrderedDict([('item1', u'test1'), ('item2', u'test2')])])]), OrderedDict([('title', u'TestTittle2), ('items', [OrderedDict([('item1', u'Fun stuff'), ('item2', None)])])])] if i use json.dumps() its gives me a json object but it changes None to null which invalidates the json I expect a Json object without replacement of None to null -
Como personalizar el queryset de de la vista generica list view en django
quiero un ejemplo de como personalizar el queryset de la listview en django, basicamente quiero aplicarle unos filtros pero no se como modificarla -
Django Model.objects.create() vs Model().save()
In Django, to create an object and save it in one line of code, the documentation suggests using the convenience method create: Model.objects.create(kwargs) Is this equivalent? Model(kwargs).save() If they are equivalent, the latter seems shorter and easier to interpret. Maybe the difference is that create forces insert. -
Celery raise MemoryError
I'm using celery 4.3.0,And use it to generate a image which maybe 10M+,Then I got an error like below: Pool callback raised exception: MemoryError('Process got: ') Traceback (most recent call last): File "*/lib/python3.7/site-packages/billiard/pool.py", line 1750, in safe_apply_callback fun(*args, **kwargs) File "*/lib/python3.7/site-packages/celery/worker/request.py", line 564, in on_success return self.on_failure(retval, return_ok=True) File "*/lib/python3.7/site-packages/celery/worker/request.py", line 351, in on_failure raise MemoryError('Process got: %s' % (exc_info.exception,)) My server has 20G+ memory left when running this task.And I had test some small images which work well.Do I need set some config to prevent this? -
problems on loading templates & admin static_files with virtualenv Django?
I have a project i developed in my machine without using any virtual environments but when i added it to the production machine and made a virtualenv it started throwing errors when loading some pages(now it's only in the sign in page and the DetailView page) and loading the admin page is just like this : and the template error gives this : My virtualenv folder is located inside the project folder just for dealing with nginx and gunicorn. while eveything work fine on my own machine. I have a static_Root and staticfiles_dir so i can't really see where's the problem. -
OneToOneField does not exist on instances of the related object
I am trying to create a one-to-one relationship between two models in different apps. It is giving me the error "RelatedObjectDoesNotExist" when I try to assign a value to that attribute. When a Table is created, no attribute is set for party. When a SeatedUser is created I create the relationship. It is telling me that SeatedUser has no table #apps/restaurants/models.py class Table(models.Model): name = models.CharField(max_length = 50) size = models.IntegerField() restaurant = models.ForeignKey(Restaurant, related_name = "tables") party = models.OneToOneField(SeatedUser, related_name = "table", null = True, default = None) createdAt = models.DateTimeField(auto_now_add = True) updatedAt = models.DateTimeField(auto_now = True) objects = RestaurantManager() #apps/users/models.py class SeatedUser(models.Model): time = models.DateTimeField(auto_now_add = True) member = models.OneToOneField(User, related_name = "seatUser", null = True) objects = DataManager() #apps/restaurants/views.py seatedUser = SeatedUser( member = lineMember.member ) seatedUser.save() seatedUser.restaurant.add(Restaurant.objects.get(line = lineMember)) seatedUser.table.add(myTable) #ERROR SeatedUser has no table lineMember.delete() I need to assign a Table to a SeatedUser, therefore assigning a SeatedUser to that Table. I cannot figure out why it is telling me that this variable doesn't exist. -
How can I save all Scrapy HTML files to S3?
I would like to set up a system to save all HTML files Scrapy finds to s3. Then before pulling any page, I would like to check if that page has already been scraped and stores to S3. I have looked at scrapy's ITEM_PIPELINES, but that seems like it's only for the parse_item function? If I have multiple spiders, it seems silly to have to add a line like: def parse(self, response): self.push_and_save_to_s3(response.text) def parse_item(self, response): self.push_and_save_to_s3(response.text) Is there some middleware I can set up that will do this automatically every time scrapy finds HTML? That way I don't have to go add this code to each parse() function and parse_item() function in my codebase. Once I have that setup, is there a way I can check all previous URLs to tell scrapy to either pull from the live webpage or our S3 bucket? -
Django templates files
Django template works fine with a .html file for me, and I have no issues with it. I was just wondering if there were any upgrades to the templates that permits the use of other kinds of files like .php for rendering. -
How to update prefix id of a formset
I'm new at python, but no at programing. I'm using Django to create a webapp and in some part, I have to create products. A product has a name, brand and type, but this product can have many "inventories". For example: The product Iphone has a brand Apple, type Phone and since I have 3 in my stock, there is another table that saves 3 individual codes for them (and the price and state as well). For this solution I have used formsets, and it was working fine without the JS. What I mean is that the process is ok, but when I want to dinamically add a new row to add a new Inventory, is added visually but then when I tried to save it, it just saves the last row. I have looked into the debug console of chrome and it seems that the problem is that the name and ID, of the new row, remains the same as the original one (the prefix I believe), but I don't know how to change it. Here is my code: (In this picture you can see that the second row has a prefix of 0, it happens the same with … -
Minimal audio (wav or mp3) file in bytes for unit testing
I want to find a minimal audio file (like the testfile_gif below) for unit testing. I don't want to load it from the hard drive (like here). I want the second test to perform like the first one. import magic from django.core.files.uploadedfile import SimpleUploadedFile class TestFiles(TestCase): def test_working(self): # Test an Image File # testfile_gif = ( b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04' b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02' b'\x02\x4c\x01\x00\x3b') gif_file = SimpleUploadedFile(name='image.gif', content=testfile_gif, content_type='image/gif') mime = magic.from_buffer(gif_file.read(1024), mime=True) self.assertEqual('image/gif', mime) def test_not_working(self): # Test an Audio File # testfile_audio = b'What should be written in here?' audio_file = SimpleUploadedFile(name='music.mp3', content=testfile_audio, content_type='audio/mpeg') mime = magic.from_buffer(audio_file.read(1024), mime=True) self.assertEqual('audio/mpeg', mime) Preferably, I don't want to use any packages (like import mock). -
JavaScript Function Doesn't Work On Django
When the first page is loaded, I want the user to come across all the music, but if he selects a list from RadioButton, I only want the music in that list, but the javascript function doesn't work. Let me add that I don't normally know JavaScript, but I need to use it. <div style = "margin-top : 100px;"class = "container"> {% for table in tables %} <input type="radio" name="list1" onclick="mL('{{table}}')"> {{table}} {% endfor %} <div align="center"> <audio class="my_audio" controls="controls" autoplay="autoplay" style="width:500px;"></audio> <ul> {% for table in tables %} {% for music in musics %} <li style="list-style-type:None"> <a id="{{table}}" href="javascript:void(0);" onclick="playSong('{{music}}')">{{music}}</a> </li> {% endfor %} {% endfor %} {% for music in musics %} <li style="list-style-type:None"> <a id="default" href="javascript:void(0);" onclick="playSong('{{music}}')">{{music}}</a> </li> {% endfor %} </ul> </div> </div> <script> function mL(x) { {% for table in tables %} if (x=={{table}}) document.getElementById("{{table}}").style.display="block"; document.getElementById("default").style.display="none"; {% endfor %} else document.getElementById("{{table}}").style.display="none"; document.getElementById("default").style.display="block"; } </script> -
Django: I try to add new group in the admin site but it does't work, the group is added but the permissions with it are not
Do I need to implement some codes for that? To make the modification in admin site effect. -
Django Using Model.objects.all() as a blueprint for a secondary DB entry
I am having a bit of trouble with the logic of how this should work so I am hoping it is possible. Overall I am working on an Apartment Move-Out/Move-In Inspection Application in Django, and in both portions I have universal Locations that must be inspected for each report. I have allowed the InspectionLocations objects to be updated/submitted by clients, which is presenting an issue in how submitted reports should be stored in my Database. What I want is to use the InspectionLocations table as a blueprint to build an Inspection Report for Move-Ins where the form-fields are generated based on the InspectionLocations objects' location, status, and information attributes/fields. My issue is right at this point, how do I reference those values as a blueprint to build a report submission when the number of fields in the InspectionLocations can change? from django.db.models import Sum from django.db.models.signals import post_save from django.dispatch import receiver from apps.units.models import Unit class Inspections(models.Model): class Meta: abstract = True id = models.AutoField(primary_key=True) inspection_date = models.DateField() submitted_by = models.ForeignKey( 'users.CustomUser', default=None, null=True, on_delete=models.SET_NULL, db_column='submitted_by') last_update = models.DateTimeField(auto_now=True) date_added = models.DateTimeField(auto_now_add=True, editable=False) class MoveInInspections(Inspections): unit = models.ForeignKey(Unit, on_delete=models.CASCADE, db_column='unit_id') # should have reference to all InspectionLocation items as … -
How to receive and save data via ajax in django?
through ajax I am sending the data correctly, because the data I see through wireshak and they are correct. On the django server, he sends me the correct request "POST / solit / HTTP / 1.1" 200 52. But the value sent does not receive it, it does not reach the Mysql database and I do not understand why, if the traffic sends well the data. In wireshak I see the data of the post request, they are the correct ones, but they are not saved in the database, when I want them to be added as if I were to update the record of such database fields and it does not , I do not understand why this is my views.py def solit(request): if request.method == 'POST' and request.is_ajax(): form = addiForm(request.POST) if form.is_valid(): peticion = form.save() if peticion.usuario: peticion.usuario.d_pendientes = form.cleaned_data.POST.get['dias_adicionar', None] # Get the form value if has, otherwise assign it to None (change it if you want another default value) peticion.usuario.h_pendientes = form.cleaned_data.POST.get['horas_adicionar', None] # The same peticion.usuario.save() print (request.get) return JsonResponse({'status': 'true', 'msg': 'Procesado Correctamente'}) else: return JsonResponse({'status': 'false', 'msg': 'Los datos no son validos'}) form = addiForm() return render(request, 'plantillas/adicionar.html', {'form':form}) This is my … -
Django app changes in server after a while
I'm running a Django app on an AWS EC2 instance. When I upload the app it works fine for a while and all of a sudden some problems appear. First, it doesn't find the media folders that initially found and second, if I fix the paths to the media folders, it returns a problem with urlpatterns, which doesn't make sense since the app works for an hour or so until it doesn't. To fix the issue I have to reupload the app but after a couple of hours it happens again. Any solutions? -
How to Embed a Plotly Interactive Graph in Webpage
I have an interactive graph generated by Plotly in Python that I saved to an html file using plotly.offline.plot(fig, filename='/tmp/interactiveGraph.html') I am now trying to embed this interactive graph into some kind of webpage, using either Dash or Django. I'm leaning toward Django at the moment, given that I have an html version of the graph. Which would be better? My code for the webpage is in a separate file from the code where I am creating the graph. A lot of the tutorials I've found online just say to add a few lines to the template, but I don't know how to get those lines that they've described. tl;dr: I'm looking for guidance as how to integrate an html file-for a Plotly interactive graph-with a web python script using Django or Dash Reference: https://github.com/ricleal/DjangoPlotLy https://www.pythonsetup.com/how-implement-data-visualization-django-and-plotly/ -
Django filter objects based on property in ForeignKey set
I have models that look something like this: class Type(models.Model): name = models.CharField(max_length=50) notes = models.CharField(max_length=50) class Instance(models.Model): type = models.ForeignKey(Type, on_delete=models.CASCADE) color = models.CharField(max_length=50) quantity = models.PositiveIntegerField() I want to get a list of all Types that have at least one Instance whose quantity is greater than 0. How can I express that? In (pseudo) vanilla Python, this would be something like: [type for type in Type.objects.all() if type.instance_set.objects.filter(lambda instance: instance.quantity > 0)] I tried available_types = Type.objects.filter(Q(instance_set__contains=Q(quantity__gt=0)) but this doesn't work because Django is looking for quantity as an attribute of Type, and of course doesn't find it, because it's an attribute of Instance. -
How to make serializer which could return list in ApiView?
I tried to make API which will return me list of "listing" id for authenticated user, but I did it without any serializer. my view : class AuthUserFavoriteListingsView(APIView): """List of favorite user listings""" permission_classes = (IsAuthenticated, ) def get(self, request): listings = UserListingFavorite.objects.filter(user=request.user).values_list('listing_id', flat=True) return Response({"listings": listings}) it is my result: { "listings": [ 9, 11 ] } Is there any way to get the same result with the serializer?