Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django image is not defined
In my html Django file every single image is runing, but one is not <img src="{% static 'img/logoR.png' %}" class="company-logo" alt="Logo"> the path of image is perfect everything is good with media, because other images are displaying I have copied that little code and pasted in the end of html tag, but is still not working. -
Django query to dict with corresponding values
I'm working on a shop project and want to be able to see what most sold products on my shop are. Here is my models.py class Product(models.Model): #some values like name, price, etc... class Purchase(models.Model): purchase_completed = models.BooleanField(default=False) # This is the only important field for this model regarding the problem that I Have # Other fields include stuff like buyers info, end price, etc... class PurchaseContains(models.Model): #Every product has its amount, purchase its related to and the product of course, with some other values as well, but not related to the problem I'm having product = models.ForeignKey(Product...) purchase = models.ForeignKey(Purchase...) amount = models.PositiveIntegerField(blank=False, null=False) Now what I want is to do a query thats going to give me what Products from PurchaseContains are bought the most (by amount from the table) and also the Purchase itself must be completed (purchase_completed==True in Purchase for the given product in PurchaseContains) Now this is what I have done: sold_the_most= PurchaseContains.objects.filter(purchase__purchase_completed=True).values("product", 'amount') sold_the_most_dict= {} for i in sold_the_most: sold_the_most_dict[i["product"]] = sold_the_most_dict.get(i['product'], 0)+i["amount"] As you can see I get the products and amount for purchases that are completed and then do the loop for it to get them in the dictionary. Now this does … -
how do I add to a JSON field in Django
AIM --- I am using Django to make a mock trading website for a project. I am running into problems trying to keep track of stocks a person owns. The problem is if someone buys 4 TSLA stocks and then 4 again it should be treated as 8 stocks of TSLA out of which they can sell 7 if they want. (BTW, I am using postgresql) Problem --- Turns out this is very difficult to do, I couldn't find anything that would help me keep track of the stocks a person owns. so, I read and read and finally turned to JSON fields. but, I am running into an issue there are well when I do u.stocks_owned = {f"{ticker}" : f"{stocks_bought_here}"} u.save() it works, it adds a key-value pair with the ticker and a number, but I don't know how to create a new row using this, or if someone already owns some stock of a company then how do I add to that?? Conclusion --- I don't need to to write code for me, just point me in the right direction I will figure it out myself! -
Django_filters multi-select dropdown with checkboxes
I am trying to create a multi-select dropdown with checkboxes for each dropdown item. I have tried Select2, but it simply returns what I already had in the first place with django_filters and formset. I have tried iterating through the choices using standard html and bootstrap, but that didn't work. To be clear, I have a properly working multi-select scroll-down box but it looks horrible; it is not a dropdown button. I want a standard drop-down with checkboxes for each item so that it is obvious to the user that multiple options can be selected. I have searched for answers on here to help, but everything seems to point to Select2 (which did not seem to get me any further in solving my problem as it yielded the same results I had originally). I have to think that this can't be difficult (though it is proving to be for me), and must be something people do pretty regularly. I am new to Django so any help is welcome. filters.py class AdvancedSearchFilter(AnimalFilter): #Inherits from Class AnimalFilter(FilterSet) filter_overides = { models.BooleanField: { 'filter_class': BooleanFilter, 'extra' : lambda f: { 'widget': forms.CheckboxInput, }, }, } class Meta: model = Animal fields = ['type', … -
I am trying to disply the search value and already filled the details but i can't see the input value of last 3 column ? Help Appricated
I have entered the data then click on the search button and I could see the other column and row display the data but I cannot see the last 3 column and row data when I clicked to search button. attached screenshot for reference. screenshot Here is my moodle.py from django.db import models from django.utils.encoding import smart_text from multiselectfield import MultiSelectField # Create your models here. class ResultQuery(models.Model): os_choice = ( ('Select an Institution', 'Select an Institution'), ('School of Management', 'School of Management'), ) operating_system = models.CharField(max_length=30, blank=True, null=True, choices=os_choice) os_choice2 = ( ('Select a level', 'Select a level'), ('Bachelor', 'Bachelor'), ('Master', 'Master'), ) level = models.CharField(max_length=30, blank=True, null=True, choices=os_choice2) os_choice3 = ( ('Select a Program', 'Select a Program'), ('MBA', 'MBA'), ('BBA', 'BBA'), ('BHM', 'BHM'), ) program = models.CharField(max_length=30, blank=True, null=True, choices=os_choice3) os_choice4 = ( ('Select a Semester', 'Select a Semester'), ('1st', '1st'), ('2nd', '2nd'), ('3rd', '3rd'), ('4th', '4th'), ('5th', '5th'), ('6th', '6th'), ('7th', '7th'), ('8th', '8th'), ) semester = models.CharField(max_length=20, blank=True, null=True, choices=os_choice4) exam_year = models.IntegerField() institute = models.CharField(max_length=4) reg_no = models.CharField(max_length=50) symbol_num = models.IntegerField() student_name = models.CharField(max_length=50) dob = models.DateField() sgpa = models.TextField() result = models.CharField(max_length=40) name = models.CharField(max_length=30) sn = models.IntegerField(max_length=222, blank=True, null=True) subject1_code=models.CharField(max_length=40) subject1_title=models.CharField(max_length=40) subject1_credit_hour=models.TextField() subject1_grade_point=models.IntegerField(max_length=212, … -
I want to update the todo list but when I try to update it add new todo task
The screenshot of my cide def updateTask(request, pk): task = Task.objects.get(id=pk) form = TaskForm(instance=task) if request.method == "POST": form = TaskForm(request.POST, instsnce=task) if form.is_valid(): form.save() return redirect('/') context = { 'form': form } return render(request, 'update_task.html', context) -
How to return queryset instead of list from Django model manager with custom SQL
I'm dealing with a legacy data source and a driver not supported by Django orm. I can only submit queries using their proprietary odbc driver via pyodbc. My workaround is to submit custom sql via pyodbc from the model manager. This techniqe (inspired by Django documentation) returns a list and not a queryset. This works great until I use packages that expect querysets. How do I convert the result list to a queryset? Is there a way to inject the results into a queryset? class MyManager(models.Manager): def getdata(self): con_string = 'DSN=myOdbcDsn;UID=id;PWD=pass' conn=pyodbc.connect(con_string) cursor=conn.cursor() result_list = [] try: sql = "select distinct coalesce(WORKCENTER_GROUP, 'na') workcenterGroup, WORKCENTER_CODE workcenterCode FROM Workcenter" cursor.execute(sql) for row in cursor.fetchall(): p = self.model(workcenterGroup=row[0], workcenterCode=row[1]) result_list.append(p) except pyodbc.Error as ex: print("----------------ERROR %s: %s" % (ex.args[0], ex.args[1])) conn.close() return result_list -
How to pass foreign key id to form? or link form to a foriegn key value DJango
I am trying to auto populate my form Student field with the name Carl Park. In short I want my form to use to automatically use the Object ID instead of having to manually select the name Carl Park from the student field drop down menu. How do I automatically link my Model Form to a foriegn key ID and have the form auto populate based on that value. Here is my current form, my models.py forms.py views.py and HTML #models class Teacher(models.Model): name = models.CharField(max_length=75) room = models.CharField(max_length=10) bio = models.TextField() class Student(models.Model): teacher = models.ForeignKey('Teacher', on_delete=models.CASCADE) name = models.CharField(max_length=75) class Student_Performance(models.Model): student = models.ForeignKey('Student', on_delete=models.CASCADE) behavior_grade = models.CharField(max_length=1) #form class StudentPerfromanceForm(ModelForm): class Meta: model = Student_Performance fields = ( "name", "behavior_grade") #view def student_details(request, id): obj = get_object_or_404(Student,pk=id) form = StudentPerfromanceForm() if request.method == 'POST': form = StudentPerfromanceForm(request.POST) if form.is_valid(): form.save(commit=True) return all_students_list(request) #pass success message return render(request, 'class_roster/student_details.html', {'obj':obj, 'reviewForm':form}) #HTML <form method="POST"> {% csrf_token %} {{reviewForm.as_p}} <input type="submit" value="Submit Review"> </form> -
DateTimeField with field specific timezone in Django admin
I'm working on a basic django application and just can't figure out a way to implement a requested feature. I have a Campaign model linked to an Alert model through a 1-n relationship. The Alert has a DateTimeField (to represent the configured alert time). However, each Alert should be able to be set for a specific timezone. I tried to override the save function to apply a the model specific timezone instance, but I can't get it to work in a satisfying manner. When displayed after save it will use the global timezone. Simplified code: import pytz from django.db import models from django.conf import settings from timezone_field import TimeZoneField class Campaign(models.Model): name = models.CharField(max_length=80, unique=True) class Alert(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, related_name='alerts') timezone = TimeZoneField(default=settings.TIME_ZONE) run_at = models.DateTimeField() def save(self, *args, **kwargs): tz = pytz.timezone(str(self.timezone)) print("Converting", self.run_at) self.run_at = self.run_at.replace(tzinfo=None) self.run_at = tz.localize(self.run_at) print("to", self.run_at) super().save(*args, **kwargs) I would appreciate if anyone had any suggestions on how to make it work properly. Or direct me to a plugin I could install to solve it (I couldn't find any). -
Django - ProgrammingError at / column <new_column> does not exist
I want to add a new field to my model. After adding and migrating I had: django.db.utils.ProgrammingError: relation already exists I've found this comment https://stackoverflow.com/a/39805907/10226040, but now I am having: ProgrammingError at / column <new_column> does not exist And migration folder isn't creating. I've deleted fields, rerunned without migration and it has worked. And I do this in Docker, BTW. Thank you. -
Many to many field all instances created are being added as relations to the models where the relation is being declared
I'm using Django-polymorphic and I think this might be the reason behind my woes. I want to have some instances of a model connected to three others through a foreign key to be added and others not, I'm not sure how to do it is there a need for an intermediate step what should I do? Here's my models: from django.db import models from polymorphic.models import PolymorphicModel from django.contrib.contenttypes.fields import GenericRelation from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class UserModel(models.Model): MEMBERSHIP_TYPE = [ ('NM', 'NORMAL'), ('PT', 'PLATA'), ('OR', 'ORO'), ('PL', 'PLATINO'), ] id = models.AutoField(primary_key=True) username = models.CharField(max_length=100, unique=True) photo = models.ImageField(upload_to='images/', blank=True) address = models.TextField() client_type = models.CharField(max_length=2, choices=MEMBERSHIP_TYPE, default= 'NM') def __unicode__(self): return self.name class ArticleModel(models.Model): id = models.AutoField(primary_key=True) code = models.IntegerField(unique=True) description = models.TextField() def __str__(self): return str(self.code) class OrderModel(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey('UserModel', on_delete=models.CASCADE) gen_time = models.DateTimeField(auto_now_add=True) gen_supplied = models.DateTimeField(null=True, blank=True) urgent = models.BooleanField() order_to = models.ForeignKey('OrderToModel', on_delete=models.CASCADE) article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE) quantity= models.IntegerField() class OrderToModel(PolymorphicModel): id = models.AutoField(primary_key=True) class WarehouseModel(OrderToModel): warehouse_num = models.IntegerField(unique=True) name = models.CharField(max_length=100) address = models.TextField() articles = models.ManyToManyField(ArticleModel, blank=True) def __str__(self): return "Warehouse"+ str(self.warehouse_num) class StoreOrderModel(OrderToModel): reference = models.IntegerField(unique=True) store_num = models.ForeignKey('StoreModel', on_delete=models.CASCADE) def __str__(self): return str(self.reference) class … -
Django: How to add select-option dropdown to a CreateView form?
This feels like an easy question, but I am not finding it in the docs or other answers online. I have a template that displays a form for a user to create a new review. I want the "Library" field on that form to be a dropdown that limits the values for that field (that is, choose from 'TV', 'Music', 'Movies' and nothing else). Here's my models.py class Review(models.Model): library = models.CharField(max_length=200) title = models.CharField(max_length=200) review_body = models.TextField(null=True) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return self.title def get_absolute_url(self): return reverse('review_detail', args=[str(self.id)]) Here's views.py class ReviewCreateView(CreateView): model = Review template_name = 'review_new.html' library_choices = ['TV', 'Movies', 'Music'] library = forms.ChoiceField(choices=library_choices) fields = ('library', 'title', 'review_body', 'author',) And here's the template: {% extends 'base.html' %} {% block content %} <h1>New Review</h1> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <button class="btn btn-success ml-2" type="submit">Save</button> </form> {% endblock content %} I got the idea to use forms.ChoiceField from this answer, but it did not work- there is just a text field in Library. Maybe it doesn't belong in the views.py? Or maybe I can't do this while subclassing CreateView and need a forms.py. -
Safely process user content in Django template language [duplicate]
I'm making a blog app in Django, where the users can write their own blog post. I have the worry that the User could introduce malicious code in the database while writing a blog post. For example, by writing javascript code in the blog post body: alert("malicious code here, ahh!) So there is any way to process the content of the user by parsing the value of the content, or something like that? -
NoReverseMatch at /add_stock Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<id>[^/]+)$']
Listed below are the files, I tried looking at the other answers on here but didn't seem to help. When I tried to output just the primary key by doing items.id on the add_stock.html page nothing came out so I'm wondering if there is an issue accessing the primary key for the database. urls.py file from django.urls import path from . import views urlpatterns = [ path('',views.home,name="home"), path('about',views.about,name="about"), path('add_stock',views.add_stock,name="add_stock"), path('delete/<stock_id>',views.delete,name="delete") ] views.py file def add_stock(request): if request.method=='POST': form = StockForm(request.POST or None) if form.is_valid(): form.save() messages.success(request,("Stock Has Been Added")) return redirect('add_stock') else: stockInfo = Stock.objects.all() ticker = [] for ticker_item in stockInfo: url = "https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-quotes" querystring = {"region":"US","lang":"en","symbols":str(ticker_item)} headers = { 'x-rapidapi-host': "apidojo-yahoo-finance-v1.p.rapidapi.com", 'x-rapidapi-key': "1ab2c68079msh721b8caa3532a08p125aafjsn601191304fe3" } api_request = requests.request("GET", url, headers=headers, params=querystring) try: api=json.loads(api_request.content) dpi=StockInfo(api['quoteResponse']['result'][0]['symbol'],api['quoteResponse']['result'][0]['regularMarketPrice'], api['quoteResponse']['result'][0]['fullExchangeName'],api['quoteResponse']['result'][0]['regularMarketChange'], api['quoteResponse']['result'][0]['regularMarketChangePercent']) ticker.append(dpi) except Exception as e: dpi="Error" return render(request,'add_stock.html',{'stockInfo':stockInfo,'ticker':ticker}) # in the add_stock html page we pass the stock_id as signature request is not passed used for completing communication def delete(request, stock_id): item = Stock.objects.get(pk=stock_id) item.delete() return redirect(add_stock)#redirect back to the page forms.py from django import forms from .models import Stock class StockForm(forms.ModelForm): class Meta: model = Stock fields = ["ticker"] -
Django test cases - data not getting loaded into default database
I am writing test cases to one of my learning project. I have added sample data via admin site, I can see that data successfully. While writing test cases for the same model, seems data not loading into test database. I am not sure what I am missing here. Any suggestions greatly appreciated. todos/models.py from django.db import models # Create your models here. class Todo(models.Model): title = models.CharField(max_length=200) body = models.TextField() def __str__(self): return self.title todos/tests.py from django.test import TestCase from .models import Todo # Create your tests here class TodoModelTest(TestCase): @classmethod def setupTestData(cls): Todo.objects.create(title='first todo', body='a body here') def test_todo_count(self): todo_count = Todo.objects.all() self.assertEqual(len(todo_count), 1) def test_title_content(self): todo = Todo.objects.get(id=1) expected_object_name = f'{todo.title}' self.assertEquals(expected_object_name, 'first todo') def test_body_content(self): todo = Todo.objects.get(id=1) expected_object_body = f'{todo.body}' self.assertEquals(expected_object_name, 'a body here') test result Creating test database for alias 'default'... System check identified no issues (0 silenced). EEF ====================================================================== ERROR: test_body_content (todos.tests.TodoModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tests.py", line 23, in test_body_content todo = Todo.objects.get(id=1) File "/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python3.9/site-packages/django/db/models/query.py", line 429, in get raise self.model.DoesNotExist( todos.models.Todo.DoesNotExist: Todo matching query does not exist. ====================================================================== ERROR: test_title_content (todos.tests.TodoModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File … -
Best way to test a web application after testing on local machine
I am working on a personal project using Django. I know very little about domains and hosting. I have tested it on my own machine (http://localhost:8000/), and now I am hoping to make it live in a way where I can have a few people log onto the website from their own computers and access it. Do I need to actually host a website to do this? Or is there some equivalent version of localhost for a select few machines for testing. -
Having issue with running django server. Keep getting the following error: AttributeError: module 'django.utils.termcolors' has no attribute 'get'
I am new to Django and this is my first ever project in it. The project was running fine but I am not sure what is happening now as I keep getting the following error when trying to run the server using the command: python3 manage.py runserver Here is the full error I am getting: Traceback (most recent call last): File "/opt/anaconda3/lib/python3.7/logging/config.py", line 543, in configure formatters[name]) File "/opt/anaconda3/lib/python3.7/logging/config.py", line 654, in configure_formatter result = self.configure_custom(config) File "/opt/anaconda3/lib/python3.7/logging/config.py", line 473, in configure_custom result = c(**kwargs) File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/utils/log.py", line 166, in __init__ self.style = color_style() File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/core/management/color.py", line 72, in color_style return make_style(os.environ.get('DJANGO_COLORS', '')) File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/core/management/color.py", line 44, in make_style format = color_settings.get(role, {}) AttributeError: module 'django.utils.termcolors' has no attribute 'get' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/utils/log.py", line 71, in configure_logging logging.config.dictConfig(DEFAULT_LOGGING) File "/opt/anaconda3/lib/python3.7/logging/config.py", line 800, in dictConfig dictConfigClass(config).configure() File "/opt/anaconda3/lib/python3.7/logging/config.py", line 546, in configure 'formatter %r' % name) from e ValueError: Unable to configure formatter 'django.server' During handling of the above exception, another exception occurred: … -
How to integrate Node JS in Django?
I'm trying to find how to implement Node JS in Django, I have seen some posts about how powerfull can they be together Django in management and Node Js in events (like this post https://www.cuelogic.com/blog/how-to-use-both-django-nodejs-as-backend-for-your-application) but I don't know how to integrate Node JS in Django and make it work it, it said that "All you need is a way to connect the socket.io server running on Node.JS with Django app." but I have no idea how to do that, so if you guys have an idea or have had work with it before I'll appreciate if you can help to this newbie trying to be a dev. -
Django Connection timed out
I'm having a problem with Django, my program can stay idle a long time between requests to the database. Sometimes in such cases I'm receiving the following error: django.db.utils.DatabaseError: SSL SYSCALL error: Connection timed out. What can be the problem and how can I fix it? I'm using PostgreSQL with psycopg2. -
How to merge **kwargs with pipe operator?
I have a model as below: # models.py class Lorem(models.Model): # ... foo_bar = models.BooleanField() foo_baz = models.BooleanField() # ... This model has fields such as foo_bar and foo_baz. I know I will query Lorem instances where foo_bar or foo_baz is True frequently in the future. So there I go create a custom QuerySet and add it to model as_manager. # models.py class LoremQuerySet(models.QuerySet): def foo(self): return self.filter(models.Q(foo_bar=True) | models.Q(foo_baz=True)) class Lorem(models.Model): # ... foo_bar = models.BooleanField() foo_baz = models.BooleanField() # ... objects = LoremQuerySet.as_manager() Up until this point, it's fine. However, in my case, I can predict I will need other fields on my Lorem model in the future, such as foo_boo or foo_bee or whatever. And any time I add these fields, I need to manually refactor LoremQuerySet.foo() to have all the fields. # LoremQuerySet.foo() # ... return self.filter(models.Q(foo_bar=True) | models.Q(foo_baz=True) | models.Q(foo_bee=True) | models.Q(foo_boo=True)) # etc # ... So, I've found a dirty workaround. I filter all attributes of Lorem starting with foo_. # LoremQuerySet.foo() # ... foo_attrs = filter(lambda s: s.startswith("foo_"), dir(Lorem)) # filter attrs starting with "lorem_" # generator resulting in ("foo_bar", "foo_baz") etc # ... However, I'm stuck at this point. How can I … -
Settings error, when triggering a scraper from a django app?
Upon starting the script that converst json data and saves it to a model, i get this error. django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Anyone know how to fix this? pipelines.py holds the script that gives the error, located in the rest_models app folder. from django.conf import settings import pandas as pd import requests # import time # from .models import * import django django.setup() from models import Article settings.configure() def add_new_articles(): # class Command(BaseCommand): fox_url = "https://saurav.tech/NewsAPI/everything/fox-news.json" fox_news = requests.get(fox_url).json() df = pd.json_normalize(fox_news) fox_articles = pd.json_normalize(df["articles"].loc[0]) del fox_articles['source.id'] fox_articles["date_publised"] = pd.to_datetime(fox_articles['publishedAt']) del fox_articles['publishedAt'] fox = fox_articles.to_records() for article in fox: article = Article( article_author=article[1], article_title=article[2], article_description=article[3], article_url=article[4], article_urlToImage=article[5], article_content=article[6], article_network=article[7], article_date_publised=article[8], ) article.save() models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings class CustomUser(AbstractUser): fav_color = models.CharField(blank=True, max_length=120) class Article(models.Model): article_author = models.CharField(blank=True, max_length=1000) article_date_publised = models.CharField(blank=True, max_length=500) article_title = models.TextField(blank=True) article_description = models.TextField(blank=True) article_url = models.TextField(blank=True) article_urlToImage = models.TextField(blank=True) article_content = models.TextField(blank=True) article_network = models.CharField(blank=True, max_length=500) -
How can i use additional fields to get jwt token
i use https://django-rest-framework-simplejwt.readthedocs.io/en/latest/ i have such code User = get_user_model() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField() ROLE_CHOICES = [ ('U', 'User'), ('M', 'Moderator'), ('A', 'Admin'), ] role = models.CharField(max_length=1, choices=ROLE_CHOICES, default='U') confirmation_code = models.CharField(max_length=30) And i want to get JWT token, here is my urls path("v1/token/", views.EmailTokenObtainPairView.as_view(), name="token_obtain_pair") i need send such POST query http://127.0.0.1:8000/api/v1/token/ with data : { 'email': email, 'confirmation_code': confirmation_code } but by default in simple-jwt i need to send data : {'username' : username, 'password':password } how can i change default way ? -
AttributeError from predicate in Django Admin when using django-rules
I am trying to create a first implementation with django-rules, following the guidelines in the README. To start with some basic concepts, I want to restrict deletion of a record to the record owner onlyin my app contact. I managed (it seems) to get things working with my API provided via Django REST Framework. However, when I open Django Admin with a non-superuser user, I get the following error: AttributeError: 'NoneType' object has no attribute 'created_by' This appears to be related to my predicate definition in contact/rules.py (I tried to follow the "book example" in the django-rules documentation here): import rules @rules.predicate def is_contact_owner(user, contact): return contact.created_by == user rules.add_perm("contact", rules.always_allow) rules.add_perm("contact.view_contact", rules.is_staff) rules.add_perm("contact.add_contact", rules.is_staff) rules.add_perm("contact.change_contact", rules.is_staff) rules.add_perm("contact.delete_contact", is_contact_owner) @rules.predicate def is_address_owner(user, address): return address.created_by == user rules.add_perm("address", rules.always_allow) rules.add_perm("address.view_address", rules.is_staff) rules.add_perm("address.add_address", rules.is_staff) rules.add_perm("address.change_address", rules.is_staff) rules.add_perm("address.delete_address", is_contact_owner) My contact/admin.py looks as follows: from django.contrib import admin from rules.contrib.admin import ObjectPermissionsModelAdmin # Register your models here. from .models import Address, Contact @admin.register(Address) class AddressAdmin(ObjectPermissionsModelAdmin): # class AddressAdmin(admin.ModelAdmin): list_display = ( "id", "local_address", "country", "uuid", "created", "modified", "created_by", "modified_by", ) date_hierarchy = "created" list_filter = ["created", "modified", "country"] @admin.register(Contact) class ContactAdmin(ObjectPermissionsModelAdmin): # class ContactAdmin(admin.ModelAdmin): list_display = ( "id", "last_name", "first_name", "date_of_birth", "uuid", … -
Facing Module Not Found Error while deploying Project in Heroku
I was trying to deploy my ecommerce website project from Heroku but I am facing this error: -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_faec937d_/store/admin.py", line 2, in <module> from .models import * ModuleNotFoundError: No module named 'store.models' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets … -
Running celery beat on windows
I work on a Celery beat task within a django project which sends emails periodically. The worker is a RabbitMQ In a development environment I use the following commands to starting the Scheduler and worker process, respectively: celery -A proj beat --loglevel=info celery -A proj worker -- loglevel=info For the above I need to activate python virtual environment and run each command in separate CMD window and it worked perfectly. However, bringing it to a production environment (daemon) on Windows is not that easy. In this post Daemonising Celery on Windows launch Celery using a batch file and configure Windows Task Scheduler to run the Celery service periodically. Which seems to be a simple solution, although I don't know how advisable My question is, what would be the correct commands from the batch file to activate the virtual environment, execute the commands described in number 1) and 2) and finally stop the services. I know it is simple but I don't know what the correct commands are. If anyone can help me I would be very grateful. The following are the steps to activate the virtual environment, run celery beat and the worker and stop the process when it is …