Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do i create bridge table in djnago model
i have created two table's in djnago models. i have created foreign-key for both models like a 'cross-product' but while i applies python3 manage.py makemigrations cmd and then python3 manage.py migrate i get error django.db.utils.IntegrityError: The row in table 'subscription_registration' with primary key '1' has an invalid foreign key: subscription_registration.ProfileImages_id contains a value '1' that does not have a corresponding value in subscription_profileimages.id. models.py table-1 class Registration(models.Model): YourName = models.CharField(max_length=30) ProfileImages = models.ForeignKey('ProfileImages', on_delete=models.CASCADE, verbose_name="profile image key(as FK)", null=True, blank=True) Email = models.EmailField(max_length=254,null=True) password = models.CharField(max_length=254,null=True) table-2 class ProfileImages(models.Model): MemeberName = models.OneToOneField('Registration',on_delete=models.CASCADE, null=True, blank=True) profile_image = models.ImageField(upload_to='profile_image',default="some",null=True) note: the registration form have allready data as id 1 now i want to add profile image for that user. and i think i can create a bridge table between them so if please help me what i can do before creating bridget table i need to assign fk for both table am right? -
Extend wagtail page visibility and add subscription plans
I'm creating a website with wagtail where users can decide to buy a subscription plan. Each subscription should allow access to a page on the site. For example, "only users in the premium plan can read the news." The subscription must have an "expiry date". At the moment the visibility can be blocked to users in a specific group (which can be managed as a subscription) but I don't know how to manage the expiration date and it doesn't seem to be a particularly elegant solution for my problem. I haven't found anything to create a custom model user_group with an expiry_date field. I would like to know how a situation like this should usually be handled and if it is possible to add another entry in the visibility section, for example: "private, accessible to users in specific subscriptions". -
How to Query model filed elements in the same URL
I am writing a single model application in DRF. My model looks like this: class Superhero(models.Model): squad_name = models.CharField(max_length=100) hometown = models.CharField(max_length=30) formed = models.DateField() active = models.BooleanField() members = JSONField() My viewset looks like this: class SuperheroViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving superheros. """ serializer_class = SuperheroSerializer def list(self, request): """list superhero object""" queryset = Superhero.objects.filter() serializer = SuperheroSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Superhero.objects.filter() superhero = get_object_or_404(queryset, pk=pk) serializer = SuperheroSerializer(superhero) return Response(serializer.data) and finally, my router is: router = DefaultRouter() router.register(r'superhero', SuperheroViewSet, basename='superhero') urlpatterns = router.urls Now how do I set a URL,so I would query the members field like: //superhero/{id}/members to get specific id members. I tried drf nested URL but didn't work. The url I have works for superhero/ and superhero/{id}. -
Error 'File doesn't exist' when running Django migrations, migrate and runserver
Whenever I run Django 'python manage.py makemigrations', runserver or migrate I get the following error : (env) mark@mysite$ python manage.py migrate File doesn't exist This is a very unhelpful error, are there any logs I can look in to find out which file is missing? I have tried re-installing Django, and deleting and recreating the site migrations and database but the error persists. The site otherwise runs fine so I have no clue as to what is going on. Any suggestions in how I can fault find this would be really appreciated. I am also using Wagtail but I don't think the error is related to that. -
channels_redis raises "Name or service not known" in docker-compose network mode bridge
I've a django app which uses channels, channels_redis and graphene_subscriptions. graphene_subscriptions is used to publish a message via channels when a database model instance is saved (DATABASE_MODEL_INSTANCE.save()). The Django app and redis (as well as the other parts of the fullstack app of course) is run separate docker containers using docker-compose. When I run the setup with docker-compose in network mode host on Linux everything is just fine. However if reconfigure the setup for network mode bridge with custom networks (one for the backend, one for the frontend) and run the setup with docker-compose I get the following error: c_backend | File "./APP_SPECIFIC_PATH/FILE.py", line X, in FUNCTION c_backend | DATABASE_MODEL_INSTANCE.save() c_backend | File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save c_backend | force_update=force_update, update_fields=update_fields) c_backend | File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 795, in save_base c_backend | update_fields=update_fields, raw=raw, using=using, c_backend | File "/usr/local/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send c_backend | for receiver in self._live_receivers(sender) c_backend | File "/usr/local/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> c_backend | for receiver in self._live_receivers(sender) c_backend | File "/usr/local/lib/python3.7/site-packages/graphene_subscriptions/signals.py", line 15, in post_save_subscription c_backend | event.send() c_backend | File "/usr/local/lib/python3.7/site-packages/graphene_subscriptions/events.py", line 20, in send c_backend | "subscriptions", {"type": "signal.fired", "event": self.to_dict()} c_backend | File "/usr/local/lib/python3.7/site-packages/asgiref/sync.py", line 116, in __call__ c_backend | return … -
In Django, form submit is working but not able to parse user input
User can able to submit the form without any issue, however user input data does not parse into database. Only predefined default data is parsing. In my opinion, my model has an issue however I could not able to find because first time I am creating an object with ForeignKey and my knowledge on 'instance' part of the model is limited. Or I am too tired... My models.py class Ticket(models.Model): ticket_id = models.AutoField(primary_key=True, unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='ticketer') status = models.CharField(max_length=6, choices=STATUS_CHOICES, default='open', blank=True) subject = models.CharField(max_length=60, default='Ticket', blank=False) body = models.TextField(blank=False) priority = models.CharField(max_length=6, choices=PRIORITY_LEVEL, default='low', blank=False) display = models.BooleanField(default=True, blank=True) created_at = models.DateTimeField(auto_now=True, blank=True) closed_at = models.DateTimeField(blank=True, null=True) handler = models.CharField(max_length=14, default='MT', blank=True) response = models.TextField(blank=True, default='We are working on your ticket!') def save(self, *args, **kwargs): super(Ticket, self).save(*args, **kwargs) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_or_update_ticket(sender, instance, created, **kwargs): Ticket.objects.create(user=instance) My views.py @login_required @transaction.atomic def add_ticket_view(request, username): if request.method == 'POST': add_ticket_form = AddTicketForm(request.POST, instance=request.user) if add_ticket_form.is_valid(): add_ticket_form.save() messages.success(request, ('Your ticket was successfully submitted!')) return redirect('..') else: messages.error(request, ('Please correct the error below.')) else: add_ticket_form = AddTicketForm(instance=request.user) context = { 'add_ticket_form': add_ticket_form, } return render(request, 'pages/user-ticket-add.html', { 'add_ticket_form': add_ticket_form }) My forms.py class AddTicketForm(forms.ModelForm): class Meta: model = Ticket fields … -
Does too many empty fields in each row effect search performance in PostgreSQL?
I am using PostgreSQL as my database along with Django Given below is my model for database class Users(model.Model): email = model.CharField(max_length=50, default="") password = model.CharField(max_length=40, default="") source = model.CharField(default='unknown', max_length=150) domain = model.CharField(max_length=50, default="") before_at = model.CharField(max_length=255, default="") username = model.CharField(max_length=150, default="") hash = model.CharField(max_length=255, default="") ipaddress = model.CharField(max_length=50, default="") phonenumber = model.CharField(max_length=100, default="") class Meta: constraints = [ models.UniqueConstraint(fields=['email', 'password', 'source'], name='uniqueness constraints') ] def __str__(self): return self.email The thing is most of the rows will have email, password, domain field but the rest will remain empty. Similarly, some will have username,password, source while others are empty. What i want to do is that everyone can search from users table based on different fields such as email, password, domain, username, hash, ipaddress. There are going to be Billions of data in this one table. So what is the best practice is it ok even if rows have a lot of empty fields or does it effect the performance. For instance there are one billion records in total but in which half a billion have empty/null ipaddress field and half billion record have data in ipaddress field then if if i gona search in the table based on ipaddress … -
why zlib error when i want to use virtualenv with python3.6?
when i run virtual environment for create environment with python3.6 in Ubuntu 16.4,i got error: **virtualenv -p python3.6 .venv** Traceback (most recent call last): File "/usr/lib/python3/dist-packages/virtualenv.py", line 22, in <module> import zlib ModuleNotFoundError: No module named 'zlib' -
Is there any way to import JavaScript function to React component outside from src folder
I have a two function at my javascript utils.js at my django static files. I want to use this file common with react. So i want to import to react this file with functions and i want to use it at react component. Function example function convertMsToDatetime(s) { let ms = s % 1000; s = (s - ms) / 1000; let secs = s % 60; s = (s - secs) / 60; let mins = s % 60; s = (s - mins) / 60; let hours = s % 24 let day = (s - hours) / 24 var ret = []; if (day !== 0) { ret.push(day + "d") } if (hours !== 0) { ret.push(hours + "h") } if (mins !== 0) { ret.push(mins + "m") } if (secs !== 0) { ret.push(secs + "s") } return ret.join(" ") } -
Django select indirectly related with a condition
In my project, I have Users and they can have a certain role. However, the roles are limited by date ranges, that is a user can have an admin role from 01.01.2020 to 02.02.2020, and an unprivileged user role from 02.02.2020 to 03.03.2020. I need to be able to return the list of users with their current roles and I want to be able to make just one query to the database. However, I can't figure out how to do that. Here are my models: class User(models.Model): ... class Role(models.Model): name = models.CharField(...) class UserRoleQuerySet(models.QuerySet): def current(): return self.filter(period__contains=date.today()) class UserRoles(models.Model): user = models.ForeignKey(User, related_name='roles') role = models.ForeignKey(Role) period = DateTimeRangeField() objects = UserRoleQuerySet.as_manager() I need a queryset with either a prefetch_related, select_related or annotate method called on it so that when I then do something like code below, I don't get additional database trips: users = User.objects.(some_magic_here).all() for user in users: print(user.profession) -
return Pandas csv as FileResponse
I have a super simple pandas table to return as csv in django: class PandasExport(View): def get(self, request, *args, **kwargs): f = tempfile.NamedTemporaryFile(mode='wt') table = pd.DataFrame(list(MyModel.objects.all().values())) report = table.to_csv(f, index=False, header=True) return FileResponse(report, 'r') Although report is fine, the view returns an error: 'NoneType' object is not iterable What am I doing wrong? -
ImageFiled not working on update in django
I have a custom form to update record in Django. everything working fine except the image. updated = Brand.objects.filter(brand_id = brand_id).update(brand_name = brand_name, brand_slug = brand_slug, brand_logo_alt_text = brand_logo_alt_text, brand_title = brand_title, category_id = brand_category, country_id = brand_country,brand_info = brand_info, brand_description = brand_desc, brand_logo = brand_logo) Media setup was perfect and everything working correct on creating new records but when I update this image not shown in media directory but in database image URL properly stored. What's exactly the problem is? and please provide a suitable solution for the same. -
How do I create a Register/Login system in Django?
I have my Django project setup, with an app called "accountManager" that manages user registeration, login and the profile page, the templates are all setup and the URLs are ready. I have already designed a form for the registeration page and the login page, so I just want to use the fields that I have in my form. I did a Google search and most of the results used the UserCreationForm which in itself is a form. Would someone tell me how do I get the information from the page and register the user? Thanks in advance -
Cross join in Django
I have a QuerySet and I need to cross join it with values list, like this SELECT table_name.*, v.flag FROM table_name CROSS JOIN (VALUES (FALSE), (TRUE)) AS v(flag) QuerySet is already initialized at this moment, so I cannot use raw method, and it is being processed further, so I need QuerySet instance in result. Is there some kind of solution to do this by using only Django ORM tools? -
Django M2M admin views
I have a problem when doing the view of a model with relation m2m in django admin. this is my model: class PagoEmpleado(models.Model): cod_pago = models.AutoField(unique=True, primary_key=True) cantidad = models.IntegerField(blank=True, null=True, default='1') monto = models.DecimalField(decimal_places=2, max_digits=20, default='0',blank=True, null=True) formula = models.CharField(max_length=250 ,blank=True, null=True) class Prenomina(models.Model): PG = ( ('obreros', 'Obreros'), ('trabajadores', 'Trabajadores'), ('ejecutivo', 'Ejecutivo'), ) cod_prenomina = models.AutoField(unique=True, primary_key=True) tipo = models.CharField(choices=PG, max_length=30, default='trabajadores') descripcion = models.CharField(max_length=20, blank=True, null=True) pagos_empleados = models.ManyToManyField(PagoEmpleado) fecha_inicio = models.DateField(blank=True, null=True) fecha_final = models.DateField(blank=True, null=True) I do not know how to represent each data in the relationship ordered in the administrator. I have read the documentation of django but I have not been able to make the view, is there a complete example to guide me? -
Error when trying to upload to AWS S3 after resizing
I am having an issue with trying to resize images before uploading to Amazon S3. I got it to work somehow on a different project that uses sqlite3 database, but i doesn't work with my latest project that uses mysql instead. Can anyone please help me out here? class UserImage(models.Model): author = models.OneToOneField(User, on_delete=models.CASCADE, null=True, default=True) myimage = models.ImageField(default='profile_pics/default-profile-picture.jpg', upload_to=profile_upload) def __str__(self): return f'{self.author.username} image' def save(self, *args, **kwargs): super().save(*args, **kwargs) img_read = storage.open(self.myimage.name, 'r') img = Image.open(img_read) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) in_mem_file = io.BytesIO() img.save(in_mem_file, format='JPEG') img_write = storage.open(self.myimage.name, 'w+') img_write.write(in_mem_file.getvalue()) img_write.close() img_read.close() -
django - not saving in other database with using()
I am doing this: user = User.objects.create( username=username, email=email, is_active=False ) user.set_password(raw_password=password) user.save() for db in settings.DATABASES: if 'default' in db: print('this is default db, so skip it: ', db) continue new_user = User( username=user.username, email=user.email, password=user.password, is_active=False ) new_user.save(using=db, force_insert=True) I am trying to "sync" one user instance into other databases. I am getting: duplicate key value violates unique constraint "auth_user_username_key" I know, it is reading from default, to check for duplicates, but even if I have "force_insert=True", it is still checking default database, therefore the error. what am I missing here? -
givin three table how to populate one by one table
enter image description here Given three table how to populate a one by one table -
Unexpected end of JSON input and 404 (Not Found)
I'm working on a chat bot system. Every time I write a message and expect a message back, I get two error messages. Uncaught (in promise) SyntaxError: Unexpected end of JSON input The error is specifically pointing on .then(response => response.json()).then((json) => { I also get error: POST http://localhost/get-response/ 404 (Not Found) which is poiting to fetch("/get-response/", { I commented it in the code below: script.js window.onload = function () { var app = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: { messages: [], input: '', send_blank: false, placeholder: 'Send a message to the chatbot...', }, created: function() { }, methods: { add_message: function() { if (this.input.length > 0) { var message = { 'text': this.input, 'user': true, 'chat_bot': false, }; this.messages.push(message); this.input = ''; //just incase this.send_blank = false; this.placeholder = "Send a message to the chatbot..."; fetch("/get-response/", { //<---- The 404 error points to this body: JSON.stringify({'message': message['text']}), cache: 'no-cache', credentials: 'same-origin', headers: { 'user-agent': 'Mozilla/4.0 MDN Example', 'content-type': 'application/json' }, method: 'POST', mode: 'cors', redirect: 'follow', referrer: 'no-referrer', }) .then(response => response.json()).then((json) => { //<--- The SyntaxError points to this this.messages.push(json['message']) }) } else { this.send_blank = true; this.placeholder = "Please put in some text"; } … -
Only the first form in Django forloop submitting data. The other forms submit empty fields
I am facing a situation whereby only the first form in the forloop in the code below can submit data. The rest of the forms after the first forloop posts empty data. What could be the problem. I believe my views is good since it's able to process the data from the first form. I believe the problem should be in the code below only that i cannot figure where the issue is When i hit submit button on the subsequent form i get the following in the shell [12/Mar/2020 12:07:17] "POST /hotels/conference/cart/twiga-boardroom-3/ HTTP/1.1" 302 0 [12/Mar/2020 12:07:18] "GET /hotels/conference/panari-hotel HTTP/1.1" 200 34389 HTML CODE <div class="room-item"> <div class="row gap-20"> <div class="col-12 col-sm-12 col-md-6"> <div class="row gap-20"> <div class="col-12 col-sm-4 col-md-4"> <div class="image"> <img src="{{ item.room_photo.url }}" alt="{{ item.object.name }}" /> </div> <p></p> {% if user.is_authenticated and item.user == user %} <a href="#" class="btn btn-primary btn-xs">Edit</a> <a href="#" class="btn btn-danger btn-xs">Delete</a> {% endif %} </div> <div class="col-12 col-sm-12 col-md-8"> <div class="content"> <h5><a href="#">{{ item.room_Name }}</a></h5> <p>{% for list in item.features_as_list %} <span class="icon-font"><i class="fas fa-check-circle text-primary"></i> {{ list }} </br></span> {% endfor %}</p> <p class="max-man">Max. Guests : <span class="badge badge-primary">{{ item.room_Capacity }}</span> <p class="price"><span class="number text-secondary"><small>Ksh</small>{{ item.room_Price|intcomma }}</span> per guest</p> … -
why django not found module psycopg2 in django2.2 and python 3.8
I install django 2.2.10 and python 3.8 and psycopg2 2.8.4 but when i try migration with command (python manage.py migrate) confront this error: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' psycopg2 in 32-bit. i try any solution that available in stackoverflow but this error don't dissolve -
Django Query filtering when all rows meet a criteria
Using django 1.11.7 and postgres we have four tables Job Table which contains job details job id test id Requirements table which contains Resource Requirements(Each Job can have multiple Requirements) Job = ForeignKey('Job') requirement_tpe = CharField() Resource: Resource ID resource status PotentialResourceRequirement Table which have a ForeignKey referring to Requirements table. Each requirement can be met by multiple resources.so there are multiple entries in PotentialResourceRequirement for each requirement with the identified resource. p_resource = models.ForeignKey('Resource') p_reequirement = models.ForeignKey('Requirement') I am looking for for a way to query the ORM providing a list of resources and identifying the job which can be run using those resources -
how to paginate django mptt queryset?
I start with an example Here is end of the first page: And here is start of the second page: Notice that "stand up" is without parent. I want to move it to the first page. Naїve solution would be: query page_size number of level 1 nodes extend queryset with descendant nodes The problem is that search will be broken. Here is example of search result (I extend result queryset with ancestors and descendants): "Alternative" has 20 more children, I don't want to show them all while searching for "indie". So naive solution will not work. Do you have any other suggestions? -
problem retrieving file from request.FILES
I have this at django @csrf_exempt @require_http_methods(['POST']) @api_token def foo(request): upload_file = request.FILES['file'] random_function(upload_file) return HttpResponse('done') and this at another python file import requests url = "http://127.0.0.1:8000/api/external/path" payload = {} files = {'file': open('csv_file.csv', 'rb')} headers = { 'x-api-key': 'api-key-token', 'Content-Type': 'application/form-data' } response = requests.request("POST", url, headers=headers, data=payload, files=files) print(response.text.encode('utf8')) the problem is that when I executed the python file I got this error django.utils.datastructures.MultiValueDictKeyError: 'file' it was like request.FILES can't find file name but when I execute it from postman it works fine -
Raspberry JavaScript bottleneck with drawImage canvas
I am trying to send frames to django backend in order to send back some predictions (JSON format). Currently we are using WebRTC getUserMedia, copying video (stream from cam) to a hidden canvas, then sending it through a web socket to the backend as binary file. It works perfectly, however, we can't achieve more than 5 fps on a PI (>30fps on regular laptop). Our bottlenecks seem drawImage (from video to canvas: 150ms on PI vs 4ms on laptop) and toBlob (canvas to binary data: 80ms on PI vs 4ms on laptop). Any idea how to improve it ? Should we definitely switch to WebRTC, or there is alternative to drawImage and toBlob ? (WebAssembly...)