Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you add validation to django rest framework api
I have two models, which look like this: class Item(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) sku = models.CharField(max_length=60) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) location = models.CharField(max_length=60) serial_number = models.CharField(max_length=60) def __str__(self): return self.name class Warehouse(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) def __str__(self): return self.name and they have two serializers which look like this: class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Item fields = ('id', 'name', 'sku', 'description', 'price', 'location', 'serial_number') #we need a validator that checks if location is in the list of warehouses #we need a validator that checks if sku is in the list of products class WarehouseSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Warehouse fields = ('id', 'name') I need a way to ensure that the location field for newly created items matches an existing name field from a warehouse. I also need the deletion of a warehouse to trigger the deletion of all items in that warehouse, or, failing that; if the warehouse has items, it cannot be deleted. I'm brand new to python and django, so any help would be massively appreciated! for reference, my views class looks like class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all().order_by('name') serializer_class = ItemSerializer class WarehouseViewSet(viewsets.ModelViewSet): queryset = Warehouse.objects.all().order_by('name') serializer_class = … -
Execute a Django view and redirect to another view like a request.POST
When I access my web page, let's say example.com, that url is associated with my index view. def index(request, pid): context = {} context['nbar'] = 'index' if request.method == 'POST': User = get_user_model() users = User.objects.all() context['users'] = users context['project_values'] = Project.objects.get(id=pid) return render(request, 'index.html', context) Inside my template (index.html) I have a button that simply changes the state of a certain project Active <-> Inactive If the user clicks the button, I want the view activate_project or deactivate_project to run in background and when the execution is finished, just reload index.html as a post.REQUEST . What I've tried: Activate - Deactivate views: def activate_project(request, pk): if request.method == 'POST': project_to_activate = ITT.objects.get(pk=pk) if project_to_activate.status == "Inactive": project_to_activate.status = "Active" project_to_activate.save() return redirect('/index/'+str(project_to_activate.id)+'/') def deactivate_project(request, pk): if request.method == 'POST': project_to_deactivate = ITT.objects.get(pk=pk) if project_to_deactivate.status == "Active": project_to_deactivate.status = "Inactive" project_to_deactivate.save() return redirect('/index/'+str(project_to_deactivate.id)+'/') The problem comes here: return redirect('/index/'+str(project_to_deactivate.id)+'/') If I use the redirect, it is treated as a GET instead of a POST. <WSGIRequest: GET '/index/5/'> In short, I need index to know that I am coming from deactivate_project or activate_project, how can I make the view index smart enough to know that? -
Django: How do I use a custom template for a specific sitemap only if I have multiple separate sitemaps?
I want to use a custom template only for a VideoSitemap when I have multiple sitemaps divided as follows: How can I use a custom template only for a specific sitemap? I want to use a custom template for VideoSitemap with a sitemap tag for Video. class VideoSitemap(Sitemap): changefreq = "weekly" def items(self): return Video.objects.published() def location(self, obj): return f"/video/{obj.pk}" def lastmod(self, obj): return obj.updated_at class PlaylistSitemap(Sitemap): ... class TagSitemap(Sitemap): ... # urls.py sitemaps = { "video": VideoSitemap, "playlist": PlaylistSitemap, "tag": TagSitemap } urlpatterns = [ path( "sitemap.xml", sitemaps_views.index, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.index", ), path( "sitemap-<section>.xml", sitemaps_views.sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), ] -
Pass List of UUID to django endpoint url as param
I have this code #VIEWS def report_pdf(request, queryset): if request.method == "GET": trans = Transaction.objects.filter(id__in=queryset) return something #URLS path("pdf/<uuid:queryset>", views.report_pdf, name="get_pdf") Now from my frontend react iam sending a get request to this endpoint with a list of UUID values. I cant find a way to access that list in my view coming from frontend. Would appreciate any suggestions! -
Getting wsgi error after updating django==3.0.12 to django==3.1.13
I'm trying to update the django version in one of my projects, however, I run into a wsgi error if I update django==3.0.12 to django==3.1.13. I get the following error- django.core.exceptions.ImproperlyConfigured: The MEDIA_URL and STATIC_URL settings must have different values. I'm not sure whether it's because of an incorrect configuration, or If there is a bug in my code. -
Error when pushing app to Heroku (psycopg2 error)
I am trying to git push my heroku app and when I execute the following command git push heroku master I get the error below. I have tried brew install postgresql, reinstalling psycopg2, installing psycopg2-binary. I have been searching for a solution and trying various ones but none seem to working. I am not too familiar with psycopg2 to know what the exact problem is so I would appreciate any help. My code is below thank you! Enumerating objects: 107, done. Counting objects: 100% (107/107), done. Delta compression using up to 4 threads Compressing objects: 100% (104/104), done. Writing objects: 100% (107/107), 17.72 MiB | 1.82 MiB/s, done. Total 107 (delta 15), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: https://github.com/heroku/heroku-buildpack-python.git remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.9.9 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.9 remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.4.1 remote: Downloading asgiref-3.4.1-py3-none-any.whl (25 kB) remote: Collecting dj-database-url==0.5.0 remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl … -
Django Rest Framework nested serializers AttributeError 'RelatedManager' object has no attribute
Full Error Got AttributeError when attempting to get a value for field segments on serializer BackboneLineSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text was: 'RelatedManager' object has no attribute 'segments'. I can't figure out why I'm getting this error. I'm using what I think is the exact same code elsewhere with it working. The only thing I can think of is I may have changed the related_name on the backbone_line field of the BackboneLineSegments model from something else to 'segments'. All migrations have been applied, and I don't know why it would be causing issues. Maybe the database doesn't update the new related_name correctly? I'm using Postgres in case it matters. Models class BackboneLine(models.Model): sub_area = models.ForeignKey( SubArea, on_delete=models.SET_NULL, null=True, related_name='backbone_lines') source = models.ForeignKey( Enclosure, on_delete=models.SET_NULL, null=True, related_name='backbone_lines_out' ) destination = models.OneToOneField( Enclosure, on_delete=models.SET_NULL, null=True, related_name='backbone_line_in' ) @property def label(self): return f'{self.source.box_number} - {self.destination.box_number}' class BackboneLineSegment(models.Model): location = models.LineStringField() buried = models.BooleanField(default=False) backbone_line = models.ForeignKey( BackboneLine, on_delete=models.CASCADE, related_name='segments' ) @property def long_lat(self): return [list(coord_pair) for coord_pair in self.location] @property def lat_long(self): return [(cords[1], cords[0]) for cords in self.location.coords] Serializers class BackboneLineSegmentSerializer(GeoFeatureModelSerializer): class Meta: model = BackboneLineSegment … -
limiting fetch data in django-celery acting as a consumer from rabbitmq queue acting as a producer
I want to retrieve 10 data message in every period of django-celery periodic task from a rabbitmq queue containing 100000 data messages. everything works well. but I don't know how can I stop fetching data if 10 data messages have been retrieve in the specific period. here is my task.py @periodic_task(run_every=(crontab(minute='*/1')), name="task", ignore_result=True) def task(): connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='name') def callback(ch, method, properties, body): # do sth channel.basic_qos(prefetch_count=10, global_qos=True) channel.basic_consume(queue='name', on_message_callback=callback) channel.start_consuming() and here is my rabbitmq producer connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='name') for i in range(10000000): channel.basic_publish(exchange='', routing_key='name', body=msg) -
No reverse match error. Reverse for 'user-profile' with arguments '('',)' not found
I have created a messaging function on my website where logged in and guest users can send messages to other users. I have created an inbox for the logged in users to store these messages. When opening up a message from a guest (someone who doesn't have an account) I get an error: Reverse for 'user-profile' with arguments '('',)' not found. Based on my digging on the web I think this may be due to the fact that the guest user doesnt have a name attached? Could this be it and how would I fix it? Views.py: def createMessage(request,pk): recipient = Profile.objects.get(id=pk) form = MessageForm() try: sender = request.user.profile except: sender = None if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): message = form.save(commit=False) message.sender = sender message.recipient = recipient if sender: message.name = sender.name message.email = sender.email message.save() messages.success(request, 'Your message was successfully sent!') return redirect('user-profile', pk=recipient.id) context = {'recipient': recipient, 'form': form} return render(request, 'users/message_form.html', context) Models.py: class Message(models.Model): sender = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True) recipient = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True, related_name="messages") name = models.CharField(max_length=200, null=True, blank=True) email = models.EmailField(max_length=200, null=True, blank=True) subject = models.CharField(max_length=200, null=True, blank=True) body = models.TextField() is_read = models.BooleanField(default=False, null=True) created = models.DateTimeField(auto_now_add=True) … -
Django How to add a User Foreignkey inside a User model?
I'm trying to insert a foreignkey of the User inside of the user model but I keep getting error. As as user I want to have two purposes, I can do i do a book to get my pets taken care of and also i can take care of other pets class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=255, default='John Doe') pet_sitter = models.ForeignKey('User',on_delete=models.CASCADE)//--->User inside User I tried get_user_model() it showed errors too// pet_appointments= models.ManyToManyField( 'User', through=Booking, through_fields=('patient', 'doctor') ) class Booking(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() owner_of_pet = models.ForeignKey(get_user_model(),related_name = "User",on_delete=models.CASCADE, blank=True,null=True) sitter = models.ForeignKey('User', on_delete=models.CASCADE) enter code here =============== error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.User' that has not been installed -
Django Constraining Foreign Keys for multiple nested objects
Let's start with the models: class Brand(models.Model): id = models.UUIDField(primary_key=True name = models.CharField(max_length=255) class ProductLine(models.Model): id = models.UUIDField(primary_key=True name = models.CharField(max_length=255) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) class Product(models.Model): id = models.UUIDField(primary_key=True name = models.CharField(max_length=255) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) product_line = models.ForeignKey(ProductLine, on_delete=models.CASCADE, blank=True, null=True) So we have brands. Brands can have 0 or more product_lines. A product always has a brand, and may also be within a product_line. My goal is to constrain the product_line of a product to also have the same brand as the product itself. For example: Brand A has 2 product_lines: Premium, Standard Brand B has 1 product_line: Platinum Suppose we have a product that belongs to brand B. I want to allow the product_line to be either null or Platinum, but not one of the product_lines that belong to Brand A (Premium or Standard) I'm not sure how to achieve this, or even if this should happen in serializers, at the model level, or somewhere else. Any help from seasoned django-ers would be much appreciated! -
Consequences of overriding __hash__ of Django models?
I have a quite complex potentially time-demanding system where Django model instances are stored and "indexed" (for the actual purpose of the system and for caching for perfomance during its execution) in sets and dicts. Thousands of CRUD operations are performed on those. Since these hashable instances are stored, this means the Django model __hashable__ method is run thousands of times: class Model(object): ... def __hash__(self): return hash(self._get_pk_val()) As efficient as this is, when called that many times, it does add up in time performance. When I use the model pk as dict keys or in sets the performance improvement is noticeable. Now, I cannot just replace all these instances with pks for practical terms, so I was thinking of overriding the method as follows in all pertinent models: def __hash__(self): return self._get_pk_val() Skipping the hash function overhead. What would be the implications and consequences of this change? Since we know the pk is unique, wouldn't this serve the same purpose in terms of indexing? Why does Django need to hash the pk? -
Add static_appname_ to file name in Django
I deploy my first app on heroku but when I download some pdf file from app their names look like static_nameapp_namefile.pdf Help me to resolve this problem -
Django loop refactor: javascript script to views.py in Highcharts
I have a script running that works, but I want to move it to "views.py". I can't seem to get the data I need because of the loop Currently working script: <script> Highcharts.chart('movements_container', { chart: {type: 'column'}, title: {text: "{{account.name}} Income/Outcome"}, plotOptions: {column: {stacking: 'normal', dataLabels: {enabled: true}}}, tooltip: {pointFormat: "Current balance: {{account.balance}} DKK"}, yAxis: {title: {text: "Movements"}}, xAxis: {title: {text: "Income/Outcome"}, type: "datetime"}, credits: {enabled: false}, series: [ {name: "Balance", data: [{{account.balance|floatformat}}], stack: "balance"}, {% for movement in account.movements %} {name: "{{account.name}}", id: "account", data: [{{movement.amount|floatformat}},], stack: "expenses", tooltip: {pointFormat: "Date: {{movement.timestamp}}</br>Transaction: {{movement.text}} </br> Amount: {{movement.amount}}"}}, {% endfor %} ], }); </script> As you can see, the big block above with "series" is what I want to translate to views.py: 12 def account_details(request, pk): 11 assert not request.user.is_staff, 'Staff user routing customer view.' 10 9 account = get_object_or_404(Account, user=request.user, pk=pk) 8 7 chart = { 6 'chart': {'type': 'column'}, 5 'title': {'text': 'test'}, 4 'yAxis': {'title': {'text': "Movements"}}, 3 'xAxis': {'title': {'text': "Income/Outcome"}}, 2 'series': [ 1 # for movement in account.movements: 49 {'name': account.name, 'data':str(account.movements)} 1 ], 3 } 5 6 context = { 7 'account': account, 8 'chart': json.dumps(chart), 10 } 11 12 return render(request, 'bank/account_details.html', context) … -
Problem with importing new Mongo database into the server
I have a Django-based website on the server. I am not really professional at this btw! So, I started the website on the server showing some data from MongoDB. This time I would like to change the DB to the newer one. This is what I am doing: First I drop the last DB: (On venv): $ mongo <db_name> --eval 'db.aggregation__class.drop' Then I scr (the new db) JSON-exported file into a server directory. Then I call the mongo to activate that new db: $ mongoimport --db <new db name> --collection <new db collection name> --file <server directory> I also checked if the db is activated by this: $ mongo <new db name> --eval And it is working. The problem is when I am calling it in the views.py, it does not show that it is connecting to the new db. Consider the fact that it was working with the last db! views.py # connect to MongoDb Database myclient = MongoClient(port=27017) mydatabase = myclient[db_name] classagg = mydatabase['aggregation__class'] database_text = classagg.find() Any suggestion would be appreciated. Thanks -
Should i go with expressjs and mongoose or django and mongoose as the backend for my website (I'm using React for the frontend)?
I have been looking at tutorials for working in the backend of my website and our team members have also thought about using django since it comes with a lot of features(mainly giving permissions to different users is easy there) whereas i don't really have a clue about how this works using express with mongodb. Since the database used for our project is gonna be non-relational(i.e mongodb), please suggest me if i should go with express or django along with mongodb, any documents references will be much appreciated! -
django form not saving on postgresql but does save to sqlite
I've deployed the project to Heroku. I'm using postgresql for my database. The job is attached to a customer table using acct_no as the foreign key. I'm able to create customers using postgresql but I can't create a job. I'm able to create a job using sqlite but when i attempt to use the postgresql database, the createview does not create a job and redirects me to my homepage. I'm fairly new to django and I've tried looking for similiar questions on here but have not been able to find a solution. models.py class Jobs(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. acct_no = models.ForeignKey(Customers, on_delete=models.CASCADE, default=1000000, db_column='ACCT_NO') # Field name made lowercase. foreman = models.CharField(db_column='FOREMAN', max_length=45, blank=True, null=True) comments = models.CharField(db_column='COMMENTS', max_length=255, blank=True, null=True) # Field name made lowercase. views.py class JobCreateView(CreateView): model = Jobs template_name = 'new_job.html' form_class = JobForm def get_initial(self): initial = super(JobCreateView, self).get_initial() initial['acct_no'] = Customers.objects.get(pk = self.kwargs['pk']) return initial def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) customer = Customers.objects.get(pk = self.kwargs['pk']) context["customer"] = customer return context def get_success_url(self): return reverse_lazy('CustomerView', kwargs = {'pk':self.kwargs['pk']}) forms.py class JobForm(forms.ModelForm): class Meta: model = Jobs fields = ['acct_no', 'job_type', 'estimatedate', 'estimatetime', 'vacant', 'year_built', 'comments'] labels = { … -
Import "django.shortcuts" could not be resolved from source
Hello, I wanted to complete my projects that I did not work for a while due to my illness, but when I opened vs code, I came across such an error. -
Save WAV file in Django backend
I am trying to record a voice message in the frontend and send it to the Django backend to test it against a ML algorithm of voice gender prediction. In the frontend I record the voice and I use AJAX to send the blob to the backend where I try to use wave to save the file as a valid .wav. The problem is that the file that gets saved on the backend is only noise without hearing the voice at all. On the frontend I can listen to the voice recording just fine, sounding exactly as it should. I am wondering how could I save on the backend the blob that I receive as a valid WAV file? Here is the recording and blob sending logic on the frontend: <div> <div id='gUMArea'> <button class="home-btn" id='gUMbtn'>Request Stream</button> </div> <div id='btns'> <button class="home-btn" id='start'>Start</button> <button class="home-btn" id='stop'>Stop</button> </div> <div> <ul class="list-unstyled" id='ul'></ul> </div> <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script> 'use strict' let log = console.log.bind(console), id = val => document.getElementById(val), ul = id('ul'), gUMbtn = id('gUMbtn'), start = id('start'), stop = id('stop'), stream, recorder, counter=1, chunks, media; gUMbtn.onclick = e => { let mv = id('mediaVideo'), mediaOptions = { audio: { tag: … -
Django button click rendered View twice
i am really new with Django and still learning. I will try to explain my problem as well as possible. On a button click in my template i want to work with some values & variables: <form method='get' action=''> <input type="submit" value="{{ answer1 }}" name="btn1" /> <input type="submit" value="{{ answer2 }}" name="btn2" /> <input type="submit" value="{{ answer3 }}" name="btn3" /> <input type="submit" value="{{ answer4 }}" name="btn4" /> </form> my views.py: class MyView(TemplateView): def get(self, request, *args, **kwargs): obj = MyObject() self.create_dict(q_obj) if request.GET.get('btn1'): # some code... return render(request, self.template_name, { ... }) The Problem is now whenever i click the button, the used dictionary variable got replaced with the next one because there is a new rendering. [12/Jan/2022 21:48:46] "GET /quizapp/home/subject/ HTTP/1.1" 200 5267 {'answer': <Answer: 3>, 'correct': False} {'answer': <Answer: 5>, 'correct': False} {'answer': <Answer: 2>, 'correct': True} {'answer': <Answer: 7>, 'correct': False} [12/Jan/2022 21:48:47] "GET /quizapp/home/subject/round/ HTTP/1.1" 200 7864 {'answer': <Answer: 4>, 'correct': True} {'answer': <Answer: 2>, 'correct': False} {'answer': <Answer: 6>, 'correct': False} {'answer': <Answer: 1>, 'correct': False} i want to work with the first set but everything i change relates to the second dictionary. I tried fixing with some redirect commands but nothing works... i am … -
Django unittest run specific test syntax
I want to run one specific unit test from my app bank/tests.py in the pipeline but I keep getting errors, I believe I am missing something on the syntax here This is my test: class SettingsTestCase(TestCase): def test_timezone_default(self): target_timezone = 'Europe/Copenhagen' self.assertEqual(target_timezone, settings.TIME_ZONE) print("Test: Correct timezone") This is how I call the test in the pipeline: ... script: - echo "Unit test...." - python manage.py test bank/tests.py:SettingsTestCase.test_timezone_default ... This is the error message when the pipeline fails: RROR: bank/tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: bank/tests Traceback (most recent call last): File "/usr/local/lib/python3.10/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) ModuleNotFoundError: No module named 'bank/tests' ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) Cleaning up project directory and file based variables 00:01 ERROR: Job failed: exit code 1 Any suggestions? -
error parsing UTF-8 params in Django app at Heroku
I have a django project running on Heroku dyno. The problem is that when I pass a query params in UTF-8 language (farsi) I got 500 error with this log message. 2022-01-12T22:11:30.432160+00:00 heroku[router]: at=info method=GET path="/api/memes/?search=%D8%AA%D8%B3%D8%AA" host=amindjangofirst.herokuapp.com request_id=dece8cd8-8a8e-489e-801a-6b1cbc3df270 fwd="184.163.35.204" dyno=web.1 connect=0ms service=83ms status=500 bytes=452 protocol=https 2022-01-12T22:11:30.431992+00:00 app[web.1]: 10.1.24.50 - - [12/Jan/2022:22:11:30 +0000] "GET /api/memes/?search=%D8%AA%D8%B3%D8%AA HTTP/1.1" 500 145 "https://amindjangofirst.herokuapp.com/api/memes/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" but if I use english characters in query everything works well also on my local machine it's working with UTF-8 params api is available at: working => https://amindjangofirst.herokuapp.com/api/memes/?search=test not-working => https://amindjangofirst.herokuapp.com/api/memes/?search=تست -
Module wsgi error when deploying Django app on apache
I had developped an application using Django (DRF). And I try to deploy it on a server. After following some tutorials on Internet, I got this error : mod_wsgi (pid=27182): Failed to exec Python script file '/my/django/project/path/myProjectName/wsgi.py'. mod_wsgi (pid=27182): Exception occurred processing WSGI script '/my/django/project/path/myProjectName/wsgi.py'. Traceback (most recent call last): File "/my/django/project/path/myProjectName/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application File "/my/django/project/path/venv/lib/python3.9/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/my/django/project/path/venv/lib/python3.9/site-packages/django/utils/version.py", line 1, in <module> import datetime File "/usr/lib/python3.9/datetime.py", line 12, in <module> import math as _math ModuleNotFoundError: No module named 'math' I had checked on some forums but I didn't find a solution to solve my problem. It seems that the problem comes from wsgi module, which is already installed when I was configure the server using this command: sudo apt install libapache2-mod-wsgi-py3 This is my V-host config: <VirtualHost *:8080> ServerAdmin webmaster@localhost # Available loglevels: trace8, ..., trace1, debug, info, no ErrorLog /my-django/project/path/error.log CustomLog /my-django/project/path/access.log combined ServerName my-domaine.com ServerAlias www.my-domaine.com DocumentRoot /my-django/project/path Alias /static /my-django/project/path/static <Directory /my-django/project/path/static> Require all granted </Directory> Alias /media /my-django/project/path/media <Directory /my-django/project/path/media> Require all granted </Directory> <Directory /my-django/project/path/myProject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /my-django/project/path/myProject/wsgi.py WSGIDaemonProcess django_app python-path=/my-django/project/path python-home=/my-django/project/path/venv WSGIProcessGroup django_app … -
Cannot reverse a Django migration using django-otp
Been trying to write the reverse code for a Django migration. Doing the migration there were no issues, but going backwards seems to be causing an issue. My migration file is below. from django.db import migrations, models def forward_migration(apps, schema_editor): totp = apps.get_model('otp_totp', 'TOTPDevice') # Doing some stuff with the devices def reverse_migration(apps, schema_editor): totp_device = apps.get_model('otp_totp', 'TOTPDevice') # Undoing some stuff with the devices class Migration(migrations.Migration): dependencies = [ ('project', 'MY_LAST_MIGRATION'), ] operations = [ migrations.RunPython(forward_migration, reverse_migration), ] When undo the migration, I get the following error: LookupError: No installed app with label 'otp_totp'. What doesn't make sense to me about this error is that if the app can't be found while undoing the migration, why were there no issues while doing the migration? The main solution to this category of problem according to SO is to check the settings.py and to ensure that the referenced app is there correctly. My INSTALLED_APPS: INSTALLED_APPS = [ ..., 'django_otp', 'django_otp.plugins.otp_totp', ... ] This would appear correct according to the django-top docs. I've also tried quite a few variants on the app_label input to get_model function and had no luck. Thank you all in advance! -
How to mock external API call inside a different request function DRF, python
In ViewSet in my DRF project: Let's say I have a post request in which I firstly get data from external api with requests.get, and then I serialize and return it as should be in post request. I am writing unittest with django unittest and I want to mock external api call. This is my first time with mock and I can't find such a case. To sum up: I have post function which gets data from external api if user hasn't passed something. I want to mock result of requests.get but I don't know how to implement it to test for post function I don't know If It would help you to get code snippets or my story is enough. If so, I can add it just let me know. Thanks to everyone that got through my story!