Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload multiple photos in Django REST admin panel
I can't find a solution to upload multiple photos to one ImageField in admin panel. I had StackedInline but it's not what I need because there each photo must be upload to new ImageField. I've gone through many questions which might have been close to mine but haven't got a solution yet. Admin panel is pretty much main part of my app. Is is possible to achieve this result in admin panel? This is how I want to see it models.py from django.db import models class User(models.Model): first_name = models.CharField(verbose_name='Имя', max_length=40) last_name = models.CharField(verbose_name='Фамилия', max_length=40) rfid_mark = models.CharField(verbose_name='RFID', max_length=10, editable=True, unique=True) registration_date = models.DateTimeField(verbose_name='Дата регистрации', auto_now=True, editable=False) def __str__(self): return self.first_name + ' ' + self.last_name class UserImage(models.Model): user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE) photo = models.ImageField(verbose_name='Фото') def __str__(self): return '' -
How to scale mysql table to keep historic data without increasing table size
I have a questionnaire in my app, using which I am creating data corresponding to user who have submitted it and at what time(I have to apply further processing on the last object/questionnaire per user). This data is saved inside my server's MySQL db. As this questionnaire is open for all my users and as it will be submitted multiple times, I do not want new entries to be created every time for same user because this will increase the size the table(users count could be anything around 10M), But I also want to keep the old data as a history for later processing. Now I have this options in mind: Create two tables. One main table to keep new object and one history table to keep history objects. Whenever a questionnaire is submitted it will create a new entry in history table, but update the existing entry in main table. So, is there any better approach to this and how other companies tackle such situations? -
How can I split orders by attributes in my API
I have a method that creates an order from the user's basket. In order for the courier to take an order from different restaurants, the order is divided into several. But at the moment I'm splitting the order just by the dish in the basket. How to make an order split by restaurants, that is, if a user orders 5 dishes from two different restaurants, then 2 orders were formed views.py @action(methods=['PUT'], detail=False, url_path='current_customer_cart/add_to_order') def add_cart_to_order(self, *args, **kwargs): cart = Cart.objects.get(owner=self.request.user.customer) cart_meals = CartMeal.objects.filter(cart=cart) data = self.request.data for cart_meal in cart_meals: order = Order.objects.create(customer=self.request.user.customer, cart_meal=cart_meal, first_name=data['first_name'], last_name=data['last_name'], phone=data['phone'], address=data.get('address', self.request.user.customer.home_address), restaurant_address=cart_meal.meal.restaurant.address, ) order.save() return response.Response({"detail": "Order is created", "added": True}) models.py class Order(models.Model): """User's order""" customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='related_orders') first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) phone = models.CharField(max_length=20) cart_meal = models.ForeignKey(CartMeal, on_delete=models.CASCADE, null=True, blank=True) restaurant_address = models.CharField(max_length=1024, null=True) address = models.CharField(max_length=1024) status = models.CharField(max_length=100, choices=STATUS_CHOICES, default=STATUS_NEW) created_at = models.DateTimeField(auto_now=True) delivered_at = models.DateTimeField(null=True, blank=True) courier = models.OneToOneField('Courier', on_delete=models.SET_NULL, null=True, blank=True) class CartMeal(models.Model): """Cart Meal""" user = models.ForeignKey('Customer', on_delete=models.CASCADE) cart = models.ForeignKey('Cart', verbose_name='Cart', on_delete=models.CASCADE, related_name='related_meals') meal = models.ForeignKey(Meal, verbose_name='Meal', on_delete=models.CASCADE) qty = models.IntegerField(default=1) final_price = models.DecimalField(max_digits=9, decimal_places=2) class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price … -
How to create the login and signup urls/views with django rest framework + firebase auth
I was trying to configure django rest framework with firebase auth. I had a look into a few tutorials and firebase doc. So far what I did is, pip install firebase-admin Create Auth class (copied): class FirebaseAuthentication(authentication.BaseAuthentication): def authenticate(self, request): auth_header = request.META.get("HTTP_AUTHORIZATION") if not auth_header: raise APIException("No auth token provided") id_token = auth_header.split(" ").pop() decoded_token = None try: decoded_token = auth.verify_id_token(id_token) except Exception: raise APIException("Invalid auth token") pass if not id_token or not decoded_token: return None try: uid = decoded_token.get("uid") except Exception: raise APIException() user, created = User.objects.get_or_create(username=uid) user.profile.last_activity = timezone.localtime() return user downloaded the config file (Generate new private key) from firebase and add that in settings, cred = credentials.Certificate(os.path.join(BASE_DIR, "firebase_config.json")) firebase_admin.initialize_app(cred) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'myauth.authentication.FirebaseAuthentication', ] } I am just a bit lost after that. Lets say, I got the uid in an android application. What would be the url or views to login/signup users? Thanks in advance. -
how to screen share using python vidstream onto a django html page?
I am trying to get the python window to show on the django html page but im not sure how to as im new to django. I followed this video "https://www.youtube.com/watch?v=8xy4JKvqsV4" to set up the python script for screen sharing Im running the receiver.py on the linux machine and the sender.py on the windows virtual machine.. receiver.py from vidstream import StreamingServer import threading receiver = StreamingServer('ipaddr', 8080) t = threading.Thread(target=receiver.start_server) t.start() while input("") != 'STOP': continue receiver.stop_server() sender.py from vidstream import ScreenShareClient import threading sender = ScreenShareClient('ipaddr', 8080) t = threading.Thread(target=sender.start_stream) t.start() while input("") != 'STOP': continue sender.stop_stream() -
Tockenizing any model instance in django (DRF)
So i am working with Django and django-rest-knox for token based authentication. It works fine but what i want now is to tokenize any other model instance instead of a user istance. Normal way; from knox.models import AuthToken AuthToken.objects.create(user=myuser) What i tried; AuthToken.objects.create(some_other_model_instace) Which gives an error; AuthToken.user" must be a "User" instance Is there any way to do so? -
Django Makemigrations fails on new autoscaling instances (shows no new changes)
We have a django backend hosted on Autoscaling ec2 instances, and during the deployments it has found that makemigrations and migrate fails (with new models added) when the new ec2 replaces in auto scaling group, as the migrations were done from the old instances, it shows no new migrations on the latest ec2. What could be the efficient solution for this - To have a separate server only for database migrations To push the migrations file directly on git/bitbucket with code so that during deployments new changes are reflected. Is there any other good solutions for this in general? -
How to view contents of one model to another model?
I am doing an Inventory App that let the user add items in the inventory and once added, they can view it in the view page of the app. they can only see it in view only mode. class Inventory(models.Model): last_modified_by = models.ForeignKey(User, on_delete=models.PROTECT) last_modified = models.DateTimeField(auto_now=True) I want to access specific items inside the Inventory Class to another model. for example I want to use last_modified_by inside for instance a Testclass. and last_modifiedin let say anotherTest class. I want to seperate the items in Inventory class in tabs, for example i have a tab inside the Test class and have all the items in it. How can i do this? -
Changing primary key in Django caused constraint does not exist error
I have Django project with DigestIssue model among others and there were Django auto created primary key field id and my field number. I wanted to get rid of duplication and set number as PK because number is unique and with same values as id. But I have foreign keys referencing this model. I doubt that they will migrate automatically after such operation. I tried, hoping for such automigration and got constraint "idx_16528_sqlite_autoindex_gatherer_digestissue_1" of relation "gatherer_digestissue" does not exist error ("sqlite" in constraint name is historical thing, I switched to PostgreSQL a time go). I tried more complicated way, following https://blog.hexack.fr/en/change-the-primary-key-of-a-django-model.html but got same error on PK switching step. So the question is - how to replace in Django old primary key with new one with same values and referenced by other models? -
CSRF follies when trying to log in to Django with Python requests/sessions
I'm trying to log in to Django using Python requests. There are old questions about this, but none of them are answered due to inadequate details. There are two CSRF tokens involved in this. One is the cookie, and the other is part of the login form. I've verified that Chrome returns the cookie token in the cookies and the form token in the body, and my url encoded body matches the format of one my browser passes back. And yet I still get "Forbidden (CSRF token missing or incorrect.)" as my response. Can any one suggest what I might be doing wrong? My Python looks like this: def login(url, username, password): session = requests.Session() response = session.get(f"{url}/accounts/login/") print(f"First headers: {response.headers}") header_csrftoken = session.cookies['csrftoken'] print(f"Header csrftoken: {header_csrftoken}") soup = BeautifulSoup(response.text, "html.parser") form = soup.find("form", {"id":"login-form"}) found = form.find("input", {"name":"csrfmiddlewaretoken"}) form_csrftoken = found['value'] print(f"csrftoken2: {form_csrftoken}") data = {'csrfmiddlewaretoken': form_csrftoken, 'username': username, 'password': password, 'next': '/'} response2 = session.post(f"{url}/accounts/login/", data=data, headers={'content-type': 'x-www-form-urlencoded'}) print(f"outgoing: {response2.request.body}") print(f"Headers: {response2.request.headers}") First headers: {'Date': 'Mon, 20 Sep 2021 03:37:17 GMT', 'Server': 'WSGIServer/0.2 CPython/3.8.12', 'Content-Type': 'text/html; charset=utf-8', 'Expires': 'Mon, 20 Sep 2021 03:37:17 GMT', 'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate, private', 'Vary': 'Cookie, Origin', 'X-Frame-Options': 'DENY', 'Content-Length': '20609', 'X-Content-Type-Options': … -
Can anyone help me with this issue - Django View (Passing of keys)
I have the following views: def device_port(request): devices = Device.objects.all() if request.method == "POST": selected=request.POST.get('device') devices = Device.objects.get(pk=selected) tablename = 'dev_interface_'+selected print("tablename: " +tablename) cursor=connection.cursor() cursor.execute(f"SELECT interface FROM {tablename} WHERE id >=2") righttable = cursor.fetchall() return redirect('/device/port/selected',{'devices':devices, 'selected': selected, 'righttable':righttable} ) return render(request, 'interface/device_port.html',{'devices':devices}) def device_port_selected(request, pk): if request.method == "POST": job = JobForm(request.POST) device = devices.hostname print(devices) #job.associateddevice = devices.hostname try: selection=request.POST.get('portrange') except: selection = "" messages.warning(request, "Please select the ports") print(selection) #job.associatedinterface = selection return render(request, 'interface/device/port/selected/'+device+'.html',{'devices':devices, 'righttable':righttable} ) return render(request, 'interface/device_port_selected.html',{'devices':devices, 'selected': selected, 'righttable':righttable} ) urls.py urlpatterns = [ path('', views.home, name='interface-home'), path('device/', DeviceListView.as_view(), name='interface-device'), path('device_edit/<int:pk>/', views.device_edit, name='device-edit'), path('device_delete/<int:pk>/', views.device_delete, name = 'device-delete'), path('device_add/', views.device_add, name='device-add'), path('device/port/', views.device_port, name='device-port'), path('device/port/selected/', views.device_port_selected, name='device-port-selected'), path('device/routeport/', views.device_routeport, name='device-routeport'), path('interface/', views.interface_list, name='interface-list') ] device_port.html <form method="POST"> <div class="form-row align-items-center"> <div class="col-md-5 my-1"> {% csrf_token %} <label for="Hostname">Hostname</label> <div class="input-group"> <select id = "list" class="custom-select mr-sm-2" onchange="getSelectValue();"> <option selected>Select</option> {% for device in devices %} <option value={{device.id}}>{{device.hostname}}</option> {%endfor%} </select> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="submit">Go</button> </div> </div> </div> </div> <input type ="text" name="device" id= "txtvalues" style="display:none"> </form> So there are 2 page I am dealing with over here. (/device/port and /device/port/selected). In this first page /device/port, user is required to pick a … -
Object creation assigns proxy class based on base model field(s)
I'm hoping to be able to create an object using a base model but have that object actually be created as a proxy class depending on the object's field(s). So for example, for the following models: class Animal(models.Model): species = models.CharField() class Cat(Animal): class Meta: proxy = True class Dog(Animal): class Meta: proxy = True How can I set it up so that cat = Animal.objects.create(species="cat") dog = Animal.objects.create(species="dog") Animal.objects.all() # Returns queryset of [cat, dog] Cat.objects.all() # Returns queryset of [cat] Dog.objects.all() # Returns queryset of [dog] -
Story object doesn't expire when User post a story feed
How do i set time for a story to expire at a certain time when users post a story, I been working on this project where i want users to be able to post a story feed for a period of time then it get deleted. Here is my story model. actually i don't really understand the way to make the post story of users to expired at a certain time like after 48 hours the post should be deleted from the story feed. class StoryManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( expire__lt=Now() ) class Story(models.Model): title = models.CharField(max_length=250) story = models.FileField(upload_to="stories",blank=True,null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) images = models.ImageField(upload_to="ImageStorie", blank=True,null=True) created = models.DateTimeField(auto_now_add=True) expire = models.DateTimeField(db_index=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name="like") image_thumbnail = ImageSpecField(source='images', processors=[ResizeToFill(500, 300)], format="JPEG", options={'quality':100}) objects = StoryManager() This my view for the story model, but the story doesn't delete after 48 hours when its been post? can someone kindly help me with this! def storie(request): context = {} videos = Story.objects.filter(expire__lt=Now()).delete() context['video'] = videos return render(request,'feed/feed.html', context) -
convert MYSQL four-table join query to Django ORM query
I have a web app, backend using Django. I want to convert a MYSQL four-table join query to the corresponding Django ORM query. The four-table join query is: 'SELECT distinct t.id, t.title as Textbook, GROUP_CONCAT(concat(ci.discipline_code, ci.code, " (" , ci.type , ")") SEPARATOR ', ') as CourseCode FROM TMS_UAT.bms_material m, TMS_UAT.bms_title t, TMS_UAT.bms_course c,TMS_UAT.bms_courseinfo ci where t.id = m.book_id and c.id = m.course_id and ci.id = c.id and isbn != "NA" GROUP BY t.id;' I want to convert it to Django ORM query and use with other filter in view.py: @csrf_exempt def Browse_and_adopt(request): Title_list = Title.objects.filter(Q(Format_issued="eText") | Q(Format_issued="Print")).select_related('publisher') //the four-table join query should be added to this , so the Title_list both have publisher and the column selected by the four-table join query -
Is there a way to seperate the description for the first image and the second image using django?
so for my website is there is 2 part to uploading an images, one is to upload images for the box and the other is to upload an images of the equipment but when it is uploaded the first image description is together with the second image description. Example shown below. Picture of what happens when it is uploaded (not I wanted) picture of what I wanted in my database. views.py @login_required() def ReceptionUnserviceable(request): descriptionbox = Photo.objects.all() if request.method == 'POST': data = request.POST images = request.FILES.getlist('images') for image in images: photo = Photo.objects.create( descriptionbox=data['descriptionbox'], image=image, serialno=data['serialno'], partno=data['partno'], reception=data['reception'], customername=data['customername'], descriptionequipment=data['descriptionequipment'], ) return redirect('success') context = {} return render(request, 'ReceptionUnserviceable.html', context) models.py class Photo(models.Model): class Meta: verbose_name = 'Photo' verbose_name_plural = 'Photos' image = models.ImageField(null=False, blank=False) descriptionbox = models.TextField() serialno = models.TextField() partno = models.TextField() reception = models.TextField() customername = models.TextField() descriptionequipment = models.TextField() def __str__(self): return self.descriptionbox Receptionunservicable.html <form method='POST' action="" enctype="multipart/form-data"> {% csrf_token %} <div> <label>Description Of The Box</label> <input required name="descriptionbox" type="text" placeholder="Enter a description" style="width:300px" class="form-control"> </div> <br> <div> <label>Upload Box Photo</label> <input required name="images" type="file" multiple class="form-control-file"> </div> <br> <div> <label>Part Number</label> <input required name="partno" type="text" placeholder="Enter part number" style="width:300px" class="form-control"> </div> <br> <div> <label>Serial … -
Why is my upload directory relative to the project directory but Django is trying to get it from an app related path?
I am building a Dev-blog to store and refer to project I've coded for my portfolio, and I've been trying to add a media upload capability to my post text boxes. I started off by using a standard RichTextField, which had a built-in function to add Images through URL(No uploading). It worked fine, but I wanted the ability to upload photos from my machine. The blog is fully operational (on a local server for development), so all irrelevant code was disregarded. The only problem is with setting the paths to my image files. models.py from django.db import models from django.utils import timezone from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): author=models.ForeignKey('auth.User',on_delete=models.CASCADE) title= models.CharField(max_length=40) text = RichTextUploadingField() create_date = models.DateTimeField(default=timezone.now()) publication_date = models.DateTimeField(blank=True,null=True) def publish(self): self.publication_date=timezone.now() self.save() def approve_comment(self): return self.comments.filter(approved_comment=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'pk':self.pk}) def ckeditor_upload(self): return reverse('post_detail', kwargs={'pk':self.pk}) urls.py from django.contrib import admin from django.urls import path,include,re_path from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), path('accounts/login/',views.LoginView.as_view(template_name='registration/login.html'),name='login'), path('accounts/logout/',views.LogoutView.as_view(),name='logout',kwargs={'next_page':'/'}), #{'next_page':'/'} makes it go back to homepage re_path(r'^ckeditor/', include('ckeditor_uploader.urls')), ] **settings.py** <pre> INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader', 'blog' ] # # # CKEDITOR_UPLOAD_PATH = 'media/uploads' The file … -
Django manytomany field automatically populates with all objects of related Model
I just added two manytomany fields to a django model; however, when I create a new instance of the model with the manytomany fields, the fields automatically contain all instances of the models they are related to. Here is the model: class Thread(models.Model): title = models.CharField(max_length=250, unique=True) owner = models.ForeignKey(AuthorUser, null=True, on_delete=models.SET_NULL, related_name='+') articles = models.ManyToManyField(Article, null=True) authors = models.ManyToManyField(AuthorUser, null=True) date_created = models.DateTimeField(default=timezone.now) And after creating a new instance of a Thread, it automatically contains all articles and authors currently in the database. Is there a way to fix this so that it starts with nothing in it and I can add authors and articles? -
Configure logger Django
I have the following code: logging.config.dictConfig( { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} - {message}', 'style': '{', }, 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'simple' } }, 'loggers': { 'django': { 'handlers': ['mail_admins'], 'level': 'INFO', 'propagate': True, }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', }, }) The problem basically exists only at the "logger". Whenever i set any of the handlers at the root key it always works, but it never reaches any of the config loggers. Any guesses? -
Python Sockets: Socket not closing when connected = False
When the disconnect message is received from my client(A django site sending the data), my socket isn't closing and this is preventing the rest of the code in my python file from running. If anybody knows what is causing this, help would be great. My Code: HEADER = 64 PORT = 6060 SERVER = '0.0.0.0' ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" my_queue = queue.Queue() print(SERVER) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): print(f"[NEW CONNECTION] {addr} connected") connected = True while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) if msg == DISCONNECT_MESSAGE: connected = False else: my_queue.put(msg) print(f"[{ADDR}] {msg}") conn.send("MSG Received".encode(FORMAT)) conn.close() def start(): server.listen() print(f"[LISTENING] Server Is Listening On {SERVER}") while True: conn, addr = server.accept() thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start() print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}") print("[Starting] Server") start() msg = my_queue.get() print(msg) -
Django MySQL Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535
I am currently migrating my tables to a new MySQL database from SQLite. There were no issues when I migrate to SQLite but when I try to migrate on to MySQL, I get the error above. I think it was due to my textfields taking up much of the space so I added a max_length=500 attribute to all of them but the error persists. This is the error: Is there a way to resize the textfield, or resize the maximum row size? Thanks in advance. -
Django URL Not Matching with Intended View
I'm having trouble figuring out why tag pages for my blog are trying to pass to a different view than the one I intend. My /tag/ url's should go to TagsListView, but instead are going to PostDetail. My url structure: app_name = 'blog' urlpatterns = [ path('', views.home, name='home'), path('search/', SearchResultsView.as_view(), name='search_results'), path('tag/<slug:slug>', views.TagsListView.as_view(), name='blog_tag'), path('<slug:slug>/', views.CategoriesDetail.as_view(), name='categories_detail'), path('<slug:categories_detail>/<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('<slug:categories_detail>/<slug:slug>/comment', views.CommentCreateView.as_view(), name='post_comment_create'), ] View: class TagsListView(ListView): model = Tag template_name = 'blog/tags.html' Template (implementation has to be dynamic): <a href="/{{ tag.slug }}"><h4><span class="badge badge-primary">{{ tag }}</span></h4></a> For some reason the url, domain.com/tag/tagname will try to match and run through the PostDetail view and 404, instead of the TagListView. Everything seems like it should match, so I'm not sure why it's skipping that over. Also, I believe I should have the model for the TagListView set to Post (blog posts), and create a custom queryset that filters based on the slug for the requested tag. Correct? Or is it the other way around? I haven't gotten to that point to test yet and wondering the best approach there. Thanks. -
Axios is sending OPTIONS instead of POST to Django
I'm using Django Rest Framework with a front-end in Vue. I'm using axios to make POST requests to Django, but the Django server is receiving OPTIONS requests, as you can see in the server log. "OPTIONS /save/ HTTP/1.1" 200 0 Broken pipe from ('127.0.0.1', 59396) The problem doesn't appear to be in the server, since CORS is configured correctly and I can send a POST request with Postman. Here's the javascript code async save() { let data = { "name": this.name, "title": this.title, } let config = { header : { "Content-Type": "application/json", } } response = await axios.post( 'http://127.0.0.1:8000/save/', data, config ) } -
Django: ModuleNotFoundError: No module named (django unable to import modules?)
When attempting to debug a file named "formulas.py", I got the following error: ModuleNotFoundError: No module named 'ingredients'. This was strange, as yesterday I debugged the file and it worked perfectly. To my knowledge, I didn't change anything that should have impeded django's ability to load my module. My file structure is the following: Blocky_alchemists blocky_alchemists ingredients media playground database manage.py In playground there are (among others) my formulas.py and views.py, and in ingredients I have my models.py which contains the model called "Ingredient". I am trying to use this model to create a queryset, so I used the following line of code in formulas.py: from ingredients.models import Ingredient When running the file formulas.py however, it runs until the above line of code, and then returns: Traceback (most recent call last): esktop\blocky_alchemists'; & 'C:\Users\ticov.virtualenvs\blocky_alchemists-KNju3Ys9\Scripts\python.exe' 'c:\Users\ticov.vscode\extension File "c:\Users\ticov\desktop\blocky_alchemists\playground\formulas.puncher' '54184' '--' 'c:\Users\ticov\desktop\blocky_alchemists\playground\formulas.py' y", line 3, in from ingredients.models import Ingredient y", line 3, in ModuleNotFoundError: No module named 'ingredients' In my main settings.py I have added 'ingredients' to the installed apps, but it is still unable to find it. Does anyone know how to fix this? Thanks in advance! -
post_save fails to create instance for OneToOneField
In attempting to use signals for the first time, I'm testing the scenario where once a User instance is created a Profile is created and is attached to the User. However, the test is not passing. I've read similar questions, but two signals are used. Django create profile for user signal Create a post_save signal that creates a profile object for me Why are two signals being used in those cases? How can I get a profile created in my case? from django.test import TestCase from ..forms import CreateProfileForm class TestNewUserProfileCreated(TestCase): '''Verify that a user profile is created once a user has registered with a username and password.''' @classmethod def setUpTestData(cls): user_submitted_data = { "username": "MockUser", "password1": "#hf7*3k", "password2": "#hf7*3k" } cls.form = CreateProfileForm(**user_submitted_data) cls.user = cls.form.save() def test_new_user_profile_form_pass(self): self.assertTrue(hasattr(self.user, 'profile')) forms.py class CreateProfileForm(UserCreationForm): def __init__(self, *args, **kwargs): pass def save(self, *args, **kwargs): pass class Meta: pass models.py class Profile(Model): user = OneToOneField( settings.AUTH_USER_MODEL, on_delete=CASCADE, related_name="profile" ) favorite_images = ManyToManyField( FavoriteImage, related_name="favorites" ) follows = ManyToManyField("self", related_name="followers") following = ManyToManyField("self", related_name="following") receivers.py from .models import Profile def create_profile_receiver(sender, instance, created, **kwargs): if created: profile = Profile.objects.create(user=instance) instance.profile = profile app.py from django.apps import AppConfig from django.conf import settings from django.db.models.signals … -
Listen for notification on React Native app from Django server
I'm currently developing a programme that will need app developers to listen out for a (ideally) silent notification from my Django server. Right now, I'm testing with a React Native app I've made but I don't know how to implement something like this. Basically, when something happens in relation to a certain app on the server end of things, I want to send a notification to that client app to react accordingly. Almost like a webhook but for mobile. It's important to know that in practice, I won't be the owner and developer of both the client-side app and the server-side software, just the server-side. If anyone knows how to do it natively on either Android or iOS that would be appreciated too.