Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I runserver I get this error: Django 405 error
Django 405 error-page not found. when I runserver I get this error.Anybody have any clue how to fix this error? I use Windows 10, python, django. [08/Apr/2023 19:54:11] "GET / HTTP/1.1" 200 3710 Not Found: /favicon.ico [08/Apr/2023 19:54:13] "GET /favicon.ico HTTP/1.1" 404 4697 [08/Apr/2023 19:54:40] "POST / HTTP/1.1" 200 3959 [08/Apr/2023 19:55:17] "GET /password/reset/ HTTP/1.1" 200 3402 [08/Apr/2023 19:55:25] "POST /password/reset/ HTTP/1.1" 302 0 [08/Apr/2023 19:55:25] "GET /password/reset/done/ HTTP/1.1" 200 3135 Method Not Allowed (POST): /password/reset/done/ Method Not Allowed: /password/reset/done/ [08/Apr/2023 19:55:28] "POST /password/reset/done/ HTTP/1.1" 405 0 My settings.py file looks like this import os from pathlib import Path from dotenv import load_dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env_path = BASE_DIR / '.env' load_dotenv(dotenv_path=env_path) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY', "error") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv("DEBUG", True) ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_crontab', 'service', 'base', 'blog', 'users', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES … -
How to stop page from refreshing when a POST request is sent using Django and AJAX
I have a browse and upload file button. I also have a Start Task button. I want to browse and select a file. After doing so, I want to click Start Task which sends a POST request and NOT have the page reload. At the moment, when I click Start Task, the selected file gets cleared out. I am new to Django and Ajax so any help is appreciated. Here is my index.html with my buttons: <div class="container-fluid px-4"> <h3 class="mt-4">Intrusion Detection System</h3> <form action="{% url 'upload' %}" class="row gy-1 gx-2 align-items-center" id='startIDS' method="post" enctype="multipart/form-data" style="margin-bottom: 10px;"> <div class='col-auto'> <input class="form-control" type="file" name="file"> </div> <div class='col-auto'> {% csrf_token %} <button type="submit" class="btn btn-primary btn-sm" style="float: right;" onclick="wait()" id="button2">Upload File</button> <script> function wait() { //go_to_sleep.delay(5); alert("Click Ok and then please wait for upload to finish"); } </script> </div> <div class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;">&nbsp;</div> </div> <div id="progress-bar-message">Waiting for progress to start...</div> <div id="celery-result"></div> <script src="{% static 'celery_progress/celery_progress.js' %}"></script> <!--CELERY--> </form> <form method="post" id="post-form"> {% csrf_token %} <button id="ajax-button" type="submit">Start task</button> </form> {% if task_id %} <script> $(document).ready(function() { $("#ajax-button").click(function(e) { e.preventDefault(); // STOP PAGE FROM REFRESHING $.ajax({ type: 'POST', url: '{% url "upload" %}', data: { csrfmiddlewaretoken: '{{ … -
I have been developing a web app in django. But whenever i make any changes to the css, it doesnt get applied
Currentlt creating a web app using Django when i ecnountered a problem. Whenever i make any changes to the css file, the webpage does not show any change. However, if i copy the contents from the css file and create a new css file and paste it there, it works perfectly. I dont know what is happening, please help. I am trying to change the css of to make some changes in the webpage but the changes are not getting applied. I have to create a new file and paste the contents from the previous css file if i want to make any changes. This new file works perfectly for sometime, then it will stop responding. Then i have to create a new css file. -
Add validation for auto populated field in django admin based on some condition
There is one model form, in which there are various fields, so all fields are filled except name field(name field can be kept blank), once we can hit submit button that name field should be auto-populated based on following code, name field length is restricted to 100, so if it exceeds that length, it gives Internal Server Error, I want to handle that ISE, instead of ISE I want to raise error(BadRequest) based on if condition mentioned in the code, but I am not able to raise it. Even I have tried with try Except, but not able to raise error, can not able to do with clean method because in this class where save_model method is defined at there NestedModelAdmin in inherited. def save_model(self, request, obj, form, change): if not obj.name: obj.name = '{}_{}'.format( obj.id, obj.model_name, ) if len(obj.name) > 100: raise BadRequest('Name cannot be longer than 100 characters.') super().save_model(request, obj, form, change) -
Django Use ModelForm to Filter database and return objects to Folium Map and table
I am trying to create a page with a Model Form, a Folium map, and a table. I want the users to be able to query the Django Model through the Model Form and have the results appear on the map and table. I am stuck trying to figure out how to use the form to query the model and how to pass the data to the map and table views. Here is my code so far. views.py import folium from django.shortcuts import render from .models import StLouisCityLandTax from .forms import StLouisCityLandTaxForm def formViewPage(request): if request.method == 'GET': form = StLouisCityLandTaxForm(request.get) if form.is_valid(): sale = form.cleaned_data['sale'] neighborho = form.cleaned_data['neighborho'] properties = StLouisCityLandTax.objects.filter(sale=sale, neighborho=neighborho) else: properties = StLouisCityLandTax.objects.all() else: form = StLouisCityLandTaxForm() properties = StLouisCityLandTax.objects.all() context = {'form': form, 'properties': properties} return render(request, 'maps/partials/_form.html', context) def allObjectsMap(request): properties = StLouisCityLandTax.objects.all() # create a Folium map centered on St Louis m = folium.Map(location=[38.627003, -90.199402], zoom_start=11) # add tile layer control and tile layer folium.TileLayer( tiles='https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', attr='Esri', name='Esri Satellite', overlay=False, control=True ).add_to(m) folium.LayerControl().add_to(m) # add markers to the map for each station for i in properties: coordinates = (i.point_y, i.point_x) # folium.Marker(coordinates).add_to(m) iframe = folium.IFrame( f"Land tax ID: {i.land_id}" + '<br>' + f"Owner: … -
I have three QuerySets from one table. 'asiento' and create lista1, lista2 and lista3
lista1 = asiento.objects.all().annotate(grupo= Substr("cuenta__codigo",1,1)).values('grupo').annotate(sum_debe=Sum("debe"),sum_haber=Sum("haber")) lista2 = asiento.objects.all().annotate(grupo = Substr("cuenta__codigo",1,3)).values('grupo').annotate(sum_debe=Sum("debe"),sum_haber=Sum("haber")) lista3 = asiento.objects.all().annotate(grupo = Substr("cuenta__codigo",1,6)).values('grupo').annotate(sum_debe=Sum("debe"),sum_haber=Sum("haber")) Chain then three QuerySets: listan = chain(lista1,lista2,lista3) The result of the chain in the variable listan is: {'grupo': '1', 'sum_debe': Decimal('251.680000000000'), 'sum_haber': Decimal('0')} {'grupo': '2', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('251.680000000000')} {'grupo': '1.0', 'sum_debe': Decimal('194.120000000000'), 'sum_haber': Decimal('0')} {'grupo': '1.2', 'sum_debe': Decimal('37.5600000000000'), 'sum_haber': Decimal('0')} {'grupo': '1.3', 'sum_debe': Decimal('20'), 'sum_haber': Decimal('0')} {'grupo': '2.1', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('143.450000000000')} {'grupo': '2.3', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('22.5600000000000')} {'grupo': '2.4', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('85.6700000000000')} {'grupo': '1.0.80', 'sum_debe': Decimal('128.450000000000'), 'sum_haber': Decimal('0')} {'grupo': '1.0.90', 'sum_debe': Decimal('65.6700000000000'), 'sum_haber': Decimal('0')} {'grupo': '1.2.00', 'sum_debe': Decimal('27.5600000000000'), 'sum_haber': Decimal('0')} {'grupo': '1.2.40', 'sum_debe': Decimal('10'), 'sum_haber': Decimal('0')} {'grupo': '1.3.20', 'sum_debe': Decimal('20'), 'sum_haber': Decimal('0')} {'grupo': '2.1.00', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('123.450000000000')} {'grupo': '2.1.50', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('20')} {'grupo': '2.3.70', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('22.5600000000000')} {'grupo': '2.4.00', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('45.6700000000000')} {'grupo': '2.4.45', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('40')} i need to order by a new field 'grupo' created in every query sets with annotate. When I sort (listan) with the chain result using the new 'grupo' field. listan = sorted(chain(lista1,lista2,lista3),key=attrgetter('grupo')) I receive the error: 'dict' object has no attribute 'grupo'. Thanks for your help. -
Select 3 random items and exclude the one already selected
I'm trying to display three random drinks in my template, selected from a database of drinks. I currently have the random selection working but also noticed theres a chance of a drink showing up twice. How do I prevent this from happening? Is there a smarter way of doing this? import random def testview(request): drink1 = random.choice(DrinkRecipe.objects.all()) drink2 = random.choice(DrinkRecipe.objects.all()) drink3 = random.choice(DrinkRecipe.objects.all()) context ={ 'drink1' : drink1, 'drink2' : drink2, 'drink3' : drink3, } return render(request,'drinks/test.html', context=context) -
Django use same object for multiple views
In django im making my first app. I'm trying to find a way to share an object between multiple view methods. e.g. In my views.py I have def lights_on(request): hue_connector = HueConnector() print(hue_connector.turn_all_lights_on()) return redirect('/') def lights_off(request): hue_connector = HueConnector() print(hue_connector.turn_all_lights_off()) return redirect('/') def light_on(request, light_id): hue_connector = HueConnector() hue_connector.set_light_on_state(light_id, "true") html = "<html><body>" + light_id + "</body></html>" return redirect('/') Lets say I want 10 more views in my views.py that need a HueConnector. How should I create one that can be used by all methods? -
why is my django app not working on browser after running python manage.py runserver 0.0.0.0:8080
while running on vagrant i try to test my django app using the command python manage.py runserver 0.0.0.0:8080 but it seems running on my device but when trying it on chrome on 127.0.0.1:8080 is not working. (profile_api) vagrant@ubuntu-bionic:/vagrant/src/profiles_project$ python manage.py runserver 0.0.0.0:8080 Performing system checks... System check identified no issues (0 silenced). April 08, 2023 - 14:43:56 Django version 1.11, using settings 'profiles_project.settings' Starting development server at http://0.0.0.0:8080/ Quit the server with CONTROL-C. 127.0.0.1 refused to connect. -
When will the data in io.bytesIO() be lost?
I am a python beginner. At what point is the data in io.bytesio() erased? Are you able to erase with this code? I want to save RAM and have higher performance. This is my code, using Django. The code creates a thumbnail after detecting the PDF upload. def file_to_thumbnail(sender, instance, created, **kwargs): if created: thumbnail_name= instance.file_name()+'_thumbnail.jpeg' thumbnail_obj =Thumbnail(file=instance) make_thumbnail = convert_from_path(instance.file.path, dpi=150, first_page=1, last_page=1, fmt='jpeg') buffer = io.BytesIO() make_thumbnail[0].save(fp=buffer, format='JPEG') thumbnail_obj.thumbnail.save(name=thumbnail_name,content=buffer) buffer.close() I want to save RAM and have higher performance. Does this code delete the io.bytesIO() data in RAM? -
How to access the correct criteriaID in HTML template django
I have a form being generated by some html and I want to use a label which is not part of the actual form data, but related to it. In the current example there are 3 criteria for the assignment and a dropdown is generated to give a student a level for each criteria and a comment about their work. The criteria description however is causing problems, as I am not sure how to fetch the correct one for each form in the formset. The context includes a list of all the criteria and so I have tried to use something like criteria.forloop.counter0 But of course this does not work. Other than this I have also tried acessing the correct criteriaDescription through the other form inputs like form.criteriaLevelID.criteriaID But this also returns nothing. I'm not sure what else to try here, but it seems like the kind of thing that there should be a simple way to achieve. The whole form looks like the below for reference <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} <table> <thead> <tr> <th>Criteria</th> <th>Criteria Level</th> <th>Comment</th> </tr> </thead> <tbody> {% for form in formset %} <tr> <td>{{ criteria # problem here }}</td> <td>{{ … -
Django error "detail: Credentials were not provided" when trying to logout
I created a class-based LogoutAPIView but when I test it, it gives the "detail: Credentials were not provided error". views.py: class LogoutView(APIView): permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] http_method_names = ['post'] def post(self, request): token = request.auth if token: Token.objects.get(token=token).delete() content = {'message': 'Logout successful'} else: content = {'message': 'No authentication token found'} return Response(content) serializer.py: class LogoutSerializer(serializers.Serializer): message = serializers.CharField(max_length=200) My LoginAPIView incase needed: views.py: class LoginAPIView(generics.CreateAPIView): permission_classes = (AllowAny,) serializer_class = LoginAPISerializer http_method_names = ['get', 'post'] def get(self, request, format=None): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data) def post(self, request, format=None): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) serializers.py: class LoginAPISerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() http_method_names = ['get', 'post'] def validate(self, data): username = data.get('username') password = data.get('password') if not username or not password: raise serializers.ValidationError('Username and password are required') user = authenticate(username=username, password=password) if not user: raise serializers.ValidationError('Invalid credentials') data['user'] = user return data def create(self, validated_data): user = validated_data['user'] token, created = Token.objects.get_or_create(user=user) return {'token': token.key} I am new to Django, so I don't even know if I need a serializer class for LogoutAPIView. I also added DEAFULT_AUTHENTICATION_CLASSES but it didn't solve the issue. Please … -
Strange behaviour because of the order of URLs in urls.py django behaviour
I am doing a mini blog assignment using Django for learning purpose. I noticed a strange behavior in django urls.py when the order of lines is below I am able to make a successful GET call to http://127.0.0.1:8000/blog/blog/create path('blog/create', views.BlogPostCreate.as_view(), name='blogpost-create'), path('blog/<slug:slug>', views.BlogPostDetail.as_view(), name='blogpost-detail'), but when the above lines are reveresed Then I start getting 404 error. I am not sure why this error is happening. By just reading the Raised By in the message I did some shot in the air and the create form start loading. Can anyone explain the behavior? I am sure there must be some explanation for this. -
Django framework. There was a question concerning creation of the dynamic form on page
I am a beginner in django. I am currently writing a test form. There was a question about creating a dynamic form to answer a question. On the page I am creating a question, as well as answers. Questions are created normally, but with the creation of answers, I did not fully understand how to implement it correctly. views.py def index(request, id): question = Profile.objects.get(id=id) answer = Question.objects.filter(ProfileId_id=question) #answer_qs = answer.objects.all() question_form_set = inlineformset_factory(Profile, Question, fields=('text_of_question', 'Weight',), extra = 0) answer_form_set = inlineformset_factory(Question, Answer, fields=('text_of_answer', 'IsRight',), extra = 0) if request.method == 'POST': formset = question_form_set(request.POST, instance=question) formset2 = answer_form_set(request.POST, queryset=answer) if formset.is_valid(): formset.save() #formset2.save() return redirect('profile') else: formset=question_form_set(instance=question) formset2 = answer_form_set(instance=answer) form = QuestionForm(request.POST or None, instance=question) form2 = AnswerForm(request.POST or None, instance=answer) return render(request, 'main/question_ch.html', {'formset': formset, 'form': form,}) models.py class Question(models.Model): ProfileId = models.ForeignKey(Profile, on_delete=models.CASCADE) text_of_question = models.CharField(verbose_name='Текст вопроса', max_length=200) Weight = models.FloatField(default=1, verbose_name='Вес') class Meta: verbose_name = 'Вопрос' verbose_name_plural = 'Вопросы' def __str__(self): return self.text_of_question class Answer(models.Model): QuestionId = models.ForeignKey(Question, on_delete=models.CASCADE) text_of_answer = models.CharField(max_length=300) IsRight = models.BooleanField() class Meta: verbose_name = 'Вариант ответа' verbose_name_plural = 'Варианты ответа' def __str__(self): return self.text_of_answer -
Combined unique_field in bulk_create in without checking PK
I am trying to import data from multiple API's and there is a chance of duplicates. I am trying to bulk-create without duplication. All API sources do not provide me with a unique identifier. I am wondering what the best way to handle this situation is. What I have tried is as follows: if 'rounds' in response: print('=== Syncing Rounds ===') rounds = response.get('rounds') objs = [ Round( name = item.get('name'), season = Season.objects.get(id = item.get('seasonId')), competition = Competition.objects.get(id = item.get('competitionId')), round_number = item.get('roundNumber'), ) for item in rounds ] Round.objects.bulk_create( objs,update_conflicts=True, update_fields=['name','season','competition','round_number'], unique_fields=['id']) I tried setting ignore_conflicts = True but that approach didn't help me. The round numbers range from 1-30 and the season is the year. In the given situation, I cannot make one field unique such as round number, season, or competition. It has to look for all three. For example There can be only one row for Round 1, 2023, for competition 112. This entire combination is unique. The end goal is to either ensure no duplicate entries or update existing rows. One hack (as said by OP) solution is Bulk insert on multi-column unique constraint Django -
Celery Beat stops running tasks without any errors
Celery beat is spinning in a container in the Kubernetes (1 replica). Celery beat works for a few days, then it stops running scheduled tasks, and there are no errors in the logs, the logs look like this: 2023-04-08 13:56:57 [2023-04-08 04:56:57,544: DEBUG/MainProcess] Current schedule: 2023-04-08 13:56:57 [2023-04-08 04:56:57,532: INFO/MainProcess] beat: Starting... 2023-04-08 13:56:57 [2023-04-08 04:56:57,532: DEBUG/MainProcess] Setting default socket timeout to 30 2023-04-08 13:56:52 . maxinterval -> 5.00 minutes (300s) 2023-04-08 13:56:52 . logfile -> [stderr]@%DEBUG 2023-04-08 13:56:52 . db -> celerybeat-schedule 2023-04-08 13:56:52 . scheduler -> celery.beat.PersistentScheduler 2023-04-08 13:56:52 . loader -> celery.loaders.app.AppLoader 2023-04-08 13:56:52 . broker -> redis://192.168.68.4:6379/3 2023-04-08 13:56:52 Configuration -> 2023-04-08 13:56:52 LocalTime -> 2023-04-07 07:38:01 2023-04-08 13:56:52 __ - ... __ - _ 2023-04-08 13:56:52 celery beat v4.3.0 (rhubarb) is starting. When celery beat stops running tasks: [2023-04-08 00:05:00,081: DEBUG/MainProcess] beat: Synchronizing schedule... [2023-04-08 00:05:00,087: DEBUG/MainProcess] 2. <crontab: 0 0 * * * (m/h/d/dM/MY)> 86099.912976 > 0 [2023-04-08 00:05:00,087: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. [2023-04-08 00:10:00,187: DEBUG/MainProcess] beat: Synchronizing schedule... [2023-04-08 00:10:00,190: DEBUG/MainProcess] 2. <crontab: 0 0 * * * (m/h/d/dM/MY)> 85799.809269 > 0 [2023-04-08 00:10:00,191: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. [2023-04-08 00:15:00,290: DEBUG/MainProcess] beat: Synchronizing schedule... [2023-04-08 00:15:00,293: DEBUG/MainProcess] … -
country flag and country code not showing in django form and admin
I'm using django-phonenumber_field in my model, but when added a PhoneNumberField in my model, and add it to my forms.py file it does not show a country flag with their country code like this in template, how can i solve this problem? from phonenumber_field.modelfields import PhoneNumberField from django.core.validators import RegexValidator class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=1000) phone_number = PhoneNumberField(validators=[RegexValidator(r'^\d{3}-\d{3}-\d{4}$')]) from phonenumber_field.formfields import PhoneNumberField class ProductForm(forms.ModelForm): phone_number = PhoneNumberField() class Meta: model = Product fields = ['name', 'category', 'description', 'phone_number'] settings.py: PHONENUMBER_DB_FORMAT = 'INTERNATIONAL' PHONENUMBER_DB_FORMAT="RFC3966" -
How to make sure data is correct after two update for the same table in Django ORM?
I use mysql and InnoDB engine for my Django project. I have a table which is like following, the queue field default value is 0 class Task(models.Model): task_id = models.CharField(max_length=32, primary_key=True) queue = models.IntegerField(default=0) I have two process, one is to insert a record based on the max queue in the table. max_queue = Task.objects.all().annotate(data=Max('queue')).values('data') queue_number = max_queue[0]['data'] + 1 record = {'task_id':task_id, 'queue': queue_number} Task.objects.create(**record) Another process is to decrement the value of queue for each record by 1 which queue is not equal to 0 query_list = Task.objects.filter(~Q(task_queue=0)) for query in query_list: Task.objects.filter(task_id=task_id).update(queue=query.queue - 1) Here what I am concerned is if the two process happened at the same time. For example, if the later process is about to decrement every value. While at the same time, the first process inserts a new value. In this case, there woule be some mistakes. How should I do it? Anyone has a good idea, thx in advance. -
amqp gets prepended to celery broker url
Specifying broker_url with redis://redis:6379/0 is getting overwritten to amqp://guest:**@redis%2F%2Fredis%3A6379%2F0:5672/ logs Cannot connect to amqp://guest:**@redis%2F%2Fredis%3A6379%2F0:5672//: [Errno -2] Name or service not known. Setup Structure config/ settings/ common.py dev.py celery.py docker-compose.yml services: django: &django_container build: context: . dockerfile: docker/django/Dockerfile command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/facebook_scraper environment: DOTTED_SETTINGS_PATH: 'config.settings.dev' env_file: - ./dev.env depends_on: - postgres - redis - selenium redis: image: redis:7.0.8 ports: - "6379:6379" celery_worker: <<: *django_container ports: [] command: celery -A config.celery worker -l INFO celery.py import os from celery import Celery dotted_settings_path = os.environ.get('DOTTED_SETTINGS_PATH') os.environ.setdefault('DJANGO_SETTINGS_MODULE', dotted_settings_path) app = Celery( 'facebook_scraper', # backend='redis://redis:6379/0', # broker='redis://redis:6379/0', ) app.conf.update( broker_url='redis://redis:6379/0', ) # app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -
Toggle theme problem is Django admin panel? [closed]
I have encountered a problem in the Django admin panel. This is running perfectly locally but not on the server. I have checked if django-extensions is installed but no its not. also, I tried setting debug to false but nothing changed... -
Django admin show only current user for User field as ForeignKey while creating and object
I'm working on a Django ( 4.0 +) project, where I have a model named Post in which we have a ForignKey field as Author, a user with is_staff and in Authors group can create an object of Post from admin. Now the problem is when user click on Add Post as the Author field it should only display the current user not the others. Here's what i have tried: From models.py: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) thumbnail = models.ImageField() category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, related_name='category') featured = models.BooleanField() status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title From admin.py: class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'status','created_on') list_filter = ("status",) search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(author=request.user) How can I achieve that? -
Django QuerySet Not returning all data
I am trying to return all the data in queryset which is saved in my model. But when I try to print it only returns the title nothing else. Bellow are the screenshots attached for refrence. Please assist Code: enter image description here and here is the data which i have saved in my model enter image description here -
Django Test Error When Using Custom User Model & django-allauth
I've been creating a Django app and am trying to get the login and authentication working correctly. I have created a custom user model to override Django's default user model and am using a Postgres backend. When I try and add django-allauth to the INSTALLED_APPS and then try and run "manage.py test" I get an error. My project structure is as follows; project/ project_app/ settings.py urls.py accounts/ models.py #CustomUser model defined in here tests.py views.py managers.py admin.py A snippet of my settings.py is; INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'accounts', 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'dj_rest_auth', 'dj_rest_auth.registration', ] AUTH_USER_MODEL = "accounts.CustomUser" When I add the line allauth.account to my settings.py file and then run "manage.py test" I get the error ValueError: Related model 'accounts.customuser' cannot be resolved. Without this line added the tests run ok. This only seems to happen when I try and run tests and not in the development database. I wondered if this was something to do with the order in which the test database is applying migrations, but don't know how to change that or if anyone else had come across this scenario. Any help much appreciated as I'm running out of ideas! -
why the hell it's popping again n again: ModuleNotFoundError: No module named 'store.product'
making a project in pycharm , after running the command : python manage.py makemigrations , its showing something like File "", line 940, in exec_module File "", line 241, in call_with_frames_removed File "C:\Users\Nisha\PycharmProjects\eshop\store_init.py", line 1, in from .product import Product ModuleNotFoundError: No module named 'store.product' (venv) PS C:\Users\Nisha\PycharmProjects\eshop> expected product python in model python package created in my __init__py so that i can go with my eshop django project. -
Django: Add is_staff permission to user inside view based on a condition
I'm working on a Django (4.0+) project,, where I'm using the default User model for login, and a custom form for signup, and I have a Boolean field named: blogger in signup form, if user check this, i have to set is_staff true, otherwise it goes as normal user. Here's what I have: Registration Form: class UserRegistrationForm(UserCreationForm): first_name = forms.CharField(max_length=101) last_name = forms.CharField(max_length=101) email = forms.EmailField() blogger = forms.BooleanField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'blogger', 'is_staff'] views.py: def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): print(form['blogger']) if form['blogger']: form['is_staff'] = True form.save() messages.success(request, f'Your account has been created. You can log in now!') return redirect('login') else: print(form.errors) else: form = UserRegistrationForm() context = {'form': form} return render(request, 'users/signup.html', context) Its giving an error as: TypeError: 'UserRegistrationForm' object does not support item assignment How can i achieve that?