Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to check foreign key attribute in one state?
I have two models in my model.py file. like this: class A(models.Model): Name=models.CharField(max_length=20) Number=models.CharField(max_length=20) Address=models.CharField(max_length=20) and class B(models.Model): Person=models.ForeginKey(A,on_delete=models.CASCADE) Code=models.CharField(max_length=20) and now I want check simple query like this, but it's wrong: object=models.B.objects.get(Person_Name='AnyName') +Note: I don't want to use this way: obj=models.A.objects.get(Name='AnyName') obj2=models.B.objects.get(Person=obj) Any other way to get directly? -
How to create a association with a model in the creation of the object?
I would like to know how can I create an other model instance just after having saved the currently model. I'm changing the original context here to post the question, but let's say I have the models above: class Owner(models.Model): name = models.CharField() points = models.IntegerField() class OwnerCars(models.Model): owner = models.ForeignKey(Owner, unique=True) total = models.IntegerField() cars = models.ManyToManyField(Cars) I would like to create the OwnerCars instance just after I have created a Owner instance, it will initialize the OwnerCars with total = 0 and also a empty list of cars. That total is going to be the sum value of all his cars when it get added. If I create a Owner object and right after that make a GET request to OwnerCars it will say that OwnerCars doesn't exist yet :(. When the person create an Owner profile, I need to have that other model to show info for the person in the screen, that's why I need that instance created. BUT..... If anyone got a better idea, I'm open for it, I know it looks like poor design, and maybe that's the problem. -
While using the django-logpipe I'm getting this error "logpipe.exceptions.MissingTopicError"
I'm running the local kafka producer to produce the messages and have created the topic "test_topic" for it. Here I have include the logpipe settings in the settings.py of my Django project.I have also mentioned the bootstrap server as my localhost machine #LOGPIPE SETTINGS in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'logpipe', ] LOGPIPE = { # Required Settings 'OFFSET_BACKEND': 'logpipe.backend.kafka.ModelOffsetStore', 'CONSUMER_BACKEND': 'logpipe.backend.kafka.Consumer', 'PRODUCER_BACKEND': 'logpipe.backend.kafka.Producer', 'KAFKA_BOOTSTRAP_SERVERS': [ 'localhost:9092' ], 'KAFKA_CONSUMER_KWARGS': { 'group_id': 'django-logpipe', }, # Optional Settings # 'KAFKA_SEND_TIMEOUT': 10, # 'KAFKA_MAX_SEND_RETRIES': 0, # 'MIN_MESSAGE_LAG_MS': 0, # 'DEFAULT_FORMAT': 'json', } -
Save a new file in the client machine directory which is selected by a user
I am working on a project(a web application that runs only on local) where a person has to select a folder and certain files are saved in the same folder based on images analysis in the same folder. I thought it would be great if I use web application than a desktop application. I used Django and used webkitdirectory mozdirectory to select a folder in HTML part. Now I need full path of the machine from which user selects the directory( to save some files in the same path). The problem is browsers have a security feature that prevents JavaScript from knowing your file's local full path. Any way I can save new file in the same folder user selects or I have to switch to desktop application like PyQT for it? -
Secure virtual money in django
I am developing a web application where the users can earn some points as a virtual currency which they could use it to buy things instead of using real money. If they do not have enough points they will need to use both points and real money. but my question is: What security measures do I have to keep in mind in order to avoid hackers increasing their points to buy things for free? The project is based on django and postgresql Any advice will be helpful -
Pass field pk of model X instead of model X's pk in ManyToMany serializer
I currently I have a request like this: { // Making request to RemoteTaskSerializer (see below) name: "Test Server", command: "ls", // TaskTarget pk's targets: [ 1, 2] } But instead of passing TaskTarget pk's, I would like to pass RemoteServer(which is a field of TaskTarget) pk's and have TaskTarget's automatically created with that server field. Here are my models/serializes: class TaskTargetSerializer(serializers.ModelSerializer): class Meta: model = TaskTarget fields = ("server",) class RemoteTaskSerializer(serializers.ModelSerializer): # targets = TaskTargetSerializer(many=True) class Meta: model = RemoteTask fields = ("name", "targets", "command", "id") class RemoteTask(models.Model): name = models.CharField(max_length=120, unique=True) targets = models.ManyToManyField(TaskTarget) command = models.TextField() class TaskTarget(models.Model): server = models.ForeignKey("RemoteServer", on_delete=models.CASCADE) output = models.TextField(null=True) class RemoteServer(models.Model): name = models.CharField(max_length=120, unique=True) ip = models.GenericIPAddressField() port = models.PositiveIntegerField() How would I go about this? -
DRf, paginate foreign key field
I wanna do something like below, but the code as it is inefficient, How can I return paginated response of related object? class Bar(models.Model): pass class Foo(models.Model): bar = models.ForeignKey('bar') foo_id = request.data.get('foo_id') foos = Foo.objects.get(id=foo_id) bars = [ foo.bar in foo for foos ] page = self.paginate_queryset(bars) serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) -
How to create an authentication system in django for a SQLServer database?
I am recently working in a django project with a SQLServer database. I already connected the database with SQLServer, and I want to make an authentication system for a table I have in that database. I know django comes with a built-in authentication system, but there is no way to tell django to use a specific table in the database to make the authentication, it just seems to look for users in the default admin page. Is there any way for django to look for data inside a specific table in a SQLServer database and validate the information put by an user? -
Comment on Post gets a page not found error, but still post the comment
I have a comment section for my post form. This is all in my post details. When a comment is posted you get a page not found error: http://localhost:8000/post/15/. post fifteen does not exist. Each comment will add to the post but the post in the error increments by one each time. views.py class PostDetail(DetailView): model = Post def get_context_data(self, **kwargs): data = super(PostDetail, self).get_context_data(**kwargs) vc = self.object.view_count self.object.view_count = F('view_count') + 1 self.object.save() self.object.view_count = vc + 1 initial_comment_data = { 'post': self.get_object(), } data['comment_form'] = CommentModelForm(initial=initial_comment_data) return data class CommentCreate(LoginRequiredMixin,CreateView): model = Comment form_class = CommentModelForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models.py class Post(models.Model): title = models.CharField(max_length=100)#title of a post content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) #if a user is deleted all of their post will be as well view_count = models.IntegerField(default=0) post_files = models.FileField(null = True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey('forum.Post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(null=True) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.text def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I want the comment to go into the correct post like it does, but with out … -
Django How to retrieve datetime object with timezone from database
I am having a difficult time with all the mumbo-jungo timezone UTC thing in python. In a django form, I create a zumba class(zumba app for a friend) and select the date and time of the class. Say I create the class for September 19, 8pm, and I am in the America/New York zone, so -4h. In the Posgres database, the entry will be 2019-09-20 00:00:00+00 Django shows it correctly in the view, as it can deal with timezone, but when I retrieve the date object afterwards in the code, I always get as if the class is happening on the 20th at midnight. The timezone offset is not taken into account. Here is the database request to retrieve the zumbaclass object. this_class = zumbaClass.objects.get(id=class_id) if I do print(this_class.date.date()) I get 2019-09-20 00:00:00+00:00 Is there a way to get the time taking the timezone into account correctly? -
I get an error while trying to create superuser in Django
I am new to Django and i am trying to create a superuser ( i'm on Linux mint) and everytime i get a very weird error that i did not get with other Django projects. The error is the following : ( I did not modify anything in the django project besides adding my app in the installed apps list and the url of the app in urls.) File "/home/user/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 538, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/user/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/user/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/.local/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/.local/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/home/user/.local/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/user/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/user/.local/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/user/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/user/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/user/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/user/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in check warnings.extend(check_resolver(pattern)) File "/home/user/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver … -
Django root url automaticlly filled
Crazy error. When I go to http://localhost:8000 instead of redirecting to http: // localhost: 8000/catalog/ I get the address in the URL http: // localhost: 8000 / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / catalog / The problem is that I removed all urlpatterns from main_app.urls, but anyway, when I access the root url I get this result. I just can’t imagine what an infinite url can generate if my url looks like this now. urlpatterns = [ url(r'^admin/', admin.site.urls), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Python/django. Good day friends
Good day friends i am currently working on an online company website that i owned For the online company, companies need to register and post their products and prices while customer need to login to their account brows through different products and pay foe the one that has a better price. Please i will be very happy to have any good tutorial for this kind of project or if someone can send me a sample model for this then i will be happy thanks. I have tried other research options but am unable to find a good one -
DJANGO FORMS.py 'RawQuerySet' object has no attribute 'all'
Hi my problem is the next, I'm trying to do a Forms with filter raw sql but I can't solved this problem 'RawQuerySet' object has no attribute 'all' Forms.py class pruebaForm (forms.Form): userid = forms.ModelChoiceField(queryset = users.objects.raw('SELECT userid FROM groupsmembers WHERE groupid=User.groupid')) softlimit = forms.IntegerField() hardlimit = forms.IntegerField() printerid = forms.ChoiceField() class Meta: model = userpquota Views.py @login_required def asignarcuota_lista (request): f = userpquotaFilter(request.GET, queryset=userpquota.objects.all()) if request.method == "POST": form = pruebaForm(request.POST) if form.is_valid(): asignarcuota = form.save(commit=False) asignarcuota.save() messages.success(request,'Se ha asignadoº correctamente') return redirect('asignarcuota_lista',) else: form = pruebaForm() return render (request, 'pykota/asignarcuota_lista.html', {'filter': f, 'form': form}) -
Reverse back Postgres field type when migrations were applied in Django
I pulled the new code from GitHub and my colleagues changed the type of a field in a Django model from TextField to JSONField. After running python manage.py makemigrations and python manage.py migrate the type of the field was changed in the database (I suppose). I needed to reverse back to previous migration and somehow the type of the field was not reversed. How could I fix the issue? Why reversing back migration does not revert back the field type? -
Why does HTTP Request result in OPTIONS rather than POST
I'm trying to do a POST request with some JSON data from an HTML page to a Django server running on localhost. Whenever I hit the button to do the POST, it results in 'OPTIONS' rather than a 'POST' I tried changing the headers for Access Control but that was to no avail. This is my javascript method. function doPost() { document.getElementById("confirmation").innerHTML = "Your order is being made."; var xhr = new XMLHttpRequest(); var url = "http://127.0.0.1:8080/app/newitem/"; xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); xhr.setRequestHeader("Access-Control-Max-Age", "600") xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var json = JSON.parse(xhr.responseText); } }; var data = JSON.stringify({"name": "Sid", "email": "testemail@testabc.com", "price": "44.99"}); xhr.send(data); } When this function was called, I expected the Django server to produce a message indicating the 'POST' occurred, instead I get [20/Sep/2019 21:36:45] "OPTIONS /app/newitem/ HTTP/1.1" 200 169 -
How to relate two models of existing database tables with specific key link?
I'm converting an excel document into a web application. I'm using Django REST as the backend, and Angular as the frontend. I have an legacy database (read-only) that has 3 tables that I want to join together to get the needed data. Basically, I'm using this to auto-populate a form. So, the user will enter a known meter number into the form, and then click a button to pull the other related information into the form - minimizing data entry. Simplified database tables and columns MeterNumber account_number meter_number Customer account_number (related to MeterNumber) mailing_address ServiceLocation account_number (related to MeterNumber) service_address So, as you can see, these tables all have the same account_number column. I'd like to be able to make a REST call to something like: server/get_data?meter_number=123456 And then the JSON response would be something like: { "account_number": 111111, "meter_number": 123456, "customer": [ { "account_number": 111111, "mailing_address: "PO Box 1234, WA 97545" } ], "service_location": [ { "account_number": 111111, "service_address: "50 Elm St, WA 85426" } ] } And this response would be used to populate the form. But how to I create these relationships based on the account_number field? Also, this database is read-only. Models: class MeterNumber(models.Model): bi_acct = … -
Django admin not showing records while still showing number
I have a model with a Foreign Key without a db_constraint. I do this so I can insert values that may not point to the foreign table. I was able to import values properly. In the Django admin, if I look at the model type that contains the constraintless foreign key, I can not see the models, but I do see a certain number of models exist. This is my code class HlaType(models.Model): specimen = models.ForeignKey(SpecimenInfo, on_delete=models.CASCADE, verbose_name="Specimen", related_name="hlatype", db_constraint=False) allele_key = models.CharField(max_length=5, db_index=True) allele = models.CharField(max_length=50, blank=True, db_index=True) class Meta: constraints = [ models.UniqueConstraint(fields=('specimen', 'allele_key'), name='targets_hlatype_unique_specimen_and_key') ] class HlaTypeAdmin(ImportExportMixin, admin.ModelAdmin): raw_id_fields = ["specimen"] list_display = ('specimen', 'allele_key', 'allele') resource_class = HlaTypeResource list_per_page = 200 class HlaTypeResource(ModelResource): specimen = Field(attribute='specimen', column_name='specimen_id', widget=HlaWidget(SpecimenInfo, 'pk')) allele_key = Field(attribute='allele_key', column_name='allele_key') allele = Field(attribute='allele', column_name='allele') class Meta: model = HlaType import_id_fields = ('specimen', 'allele_key') skip_unchanged = True fields = ('id', 'specimen', 'allele_key', 'allele') Any idea how to remedy this? -
List of model fields with missing values nicely formatted in Django template
I'm trying to make a view in Django to list each entry in a model and any of the fields that are missing values. The template is a table: one column is a specific field and the other column is a list of the fields with missing values. I have a working version, but the missing fields are just strung together, and I'd like to have them nicely formatted with commas in between. #models.py class exif(models.Model): image = models.ForeignKey('image', on_delete=models.CASCADE, blank=False, null=False) filename = models.CharField(max_length=100, blank=True, null=True) artist = models.CharField(max_length=100, blank=True, null=True) copyright = models.CharField(max_length=100, blank=True, null=True) keywords = models.CharField(max_length=100, blank=True, null=True) caption = models.CharField(max_length=100, blank=True, null=True) comment = models.CharField(max_length=100, blank=True, null=True) ... #views.py def exif_export(request): exif_records = serializers.serialize("python", exif.objects.all()) return render(request, 'exif_export.html', {'exif_records': exif_records}) #exif_export.html <table> <tr> <th>File</th> <th>Missing Exif Fields</th> </tr> {% for record in exif_records %} <tr> <td> {% for field, value in record.fields.items %} {% if field == 'filename' %} {{ value }} {% endif %} {% endfor %} </td> <td> {% for field, value in record.fields.items %} {% if not value %} {{ field }}, <!-- This comma makes a trailing comma at the end of the list --> {% endif %} {% endfor %} … -
How to use components of an admin page in another page?
I have customized the "change_form_template" of an object in my Django admin panel. I want to add a table in my new page but I don't want to code the functionalities of the table from the scratch. I would like to know is there any way to some how use the "change_list_template" page table and its functionalities in my new page? -
Problem redirecting to file from post link
I am having trouble with redirecting the link to the proper file when a link inside the post is clicked. The file is stored in a media and can be viewed from localhost/media/filename.pdf with no issues. Inside of post_detail.html <a href="/media/{{ object.post_files }}">{{ object.post_files }}</a> My urls.py urlpatterns = [ path('', PostList.as_view(), name='forum-home'), path('about/', views.about, name='forum-about'), path('post/new/', PostCreate.as_view(), name='post-create'), path('post/<int:pk>/', PostDetail.as_view(), name='post-detail'), path('post/<int:pk>/update/', PostUpdate.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDelete.as_view(), name='post-delete'), path('post/comment/', CommentCreate.as_view(), name='add_comment_to_post'), ] I'm assuming this is a path error because the error is:http://localhost:8000/post/4/media/filename.pdf This would mean it is checking staying with in post. -
Django: How to check a Form with a m2m relation object already exists or is “unique_together”?
I am testing forms and nesting models in django. In my Project a Person can enter departure, arrival (city names) and choose a weekly day (Mon-Fri). Maybe he drives every “Tuesday” from Amsterdam to Paris. I wanted this constellation to be unique – just for fun. So If another user enters the same route the relation should be linked to the same Car.object. Models.py class Person(models.Model): name = models.CharField(max_length=255, blank=False, unique=True) route = models.ManyToManyField('Car') def __str__(self): return self.name class Car(models.Model): name = models.CharField(max_length=255, blank=False, unique=True) weekdays = models.ForeignKey('Week', null=True, blank=False, on_delete=models.SET_NULL) departure = models.CharField(max_length=255, blank=False) arrival = models.CharField(max_length=255, blank=False) class Meta: unique_together = ['weekdays', 'departure', 'arrival'] # --- Unique combination def __str__(self): return self.name class Week(models.Model): day = models.CharField(max_length=255, blank=False, unique=True) def __str__(self): return self.day views.py class RouteCreateView(CreateView): model = Person template_name ="testa/create_route.html" form_class = RouteForm success_url = reverse_lazy('testa:testa_home') def form_valid(self, form): return super().form_valid(form) forms.py class RouteForm(forms.ModelForm): # --- apply ChoiceField day = forms.ModelChoiceField(queryset=None) car_name = forms.CharField() departure = forms.CharField() arrival = forms.CharField() class Meta: model = Person fields = [ 'name' ] def __init__(self, *args, **kwargs): super(RouteForm, self).__init__(*args, **kwargs) self.fields['day'].queryset = Week.objects.all() def save(self, commit=True): personData = super().save(commit) data = self.cleaned_data carData = Car(name=data['car_name'], weekdays=data['day'], departure=data['departure'], arrival=data['arrival']) if commit: … -
How do I add image to object in Python?
Seemingly trivial question, but I'm stuck. I'm trying to add add a photo to a model's ImageField when I create the model. But I don't know how to specify the photo. Do I specify the path, or a photo object? class MyModel(models.Model): img = models.ImageField() # I tried these, none works from PIL import Image MyModel.objects.create(img='img.jpg') MyModel.objects.create(img=Image.open('img.jpg')) MyModel.objects.create(img=open('img.jpg', 'r')) MyModel.objects.create(img=open('img.jpg', 'w')) -
How to select and deselect options if multiselect option coming from ajax response
<div class="content-section"> <form method="POST" id="moviesForm" ajax_load_cast="{% url 'ajax_load_cast' %}" novalidate enctype="multipart/form-data" > {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"></legend> <div class="form-group"> <label for="id_cast" class="col-form-label requiredField">Cast<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="cast" value="" maxlength="50" class="textinput textInput form-control" required="" id="id_cast"> <select id="add_cast2" multiple style="width:100%" ></select> </div> </div> <div id="" class="form-group"> </div> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% block js%} <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var ajaxResult=[]; $("#id_cast").keyup(function () { var url = $("#moviesForm").attr("ajax_load_cast"); var text_input = $('#id_cast').val(); $.ajax({ url: url, data: { 'text_input': text_input }, success: function (data) { $("#add_cast2").html(data); } }); }); </script> {% endblock js%} {% endblock content %} I am implementing a django multiselect option formField with basic html and ajax request so that it filters results before showing all the results. But I don't know how to implement select and deselect with the ajax response that brings multiselect options from database. With each response it deselects the selected options. -
Create several instances out of a related model in Django
In university as a part of a project we have to develop a liga system with Django. I have my basic app running and also my models are already set up. from django.db import models from datetime import datetime # Create your models here. class Player(models.Model): vorname = models.CharField(max_length=30) nachname = models.CharField(max_length=50) created_on = models.DateTimeField(auto_now_add=True) email = models.EmailField() class Liga(models.Model): name = models.CharField(max_length=50) participants = models.ManyToManyField(Player) created_on = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=False) is_completed = models.BooleanField(default=False) class Game(models.Model): liga = models.ForeignKey(Liga, on_delete='DO NOTHING') player1 = models.CharField(max_length=100) player2 = models.CharField(max_length=100) score_pl1 = models.IntegerField(blank=True) score_pl2 = models.IntegerField(blank=True) is_completed = models.BooleanField(default=False) completed_on = models.DateTimeField(auto_now_add=True) Now when I've created a new liga in the admin area I want Django to automatically create the Game instances (wich could be several). I've tried several different ways to do that but couldn't fix that problem.