Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deal with NoReverseMatch Error in Django
I am having this error below: Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/$']. I am working on a blog app. When you click on view more article on your dashboard on index page, the post_detail.html should show the full article and allow users to post comments. I keep getting the error posted above once i click on view article. Here is the post_detail.html code {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-8 card mb-4 mt-3 left top"> <div class="card-body"> <h1>{% block title %} {{ post.title }} {% endblock title %}</h1> <p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p> <p class="card-text ">{{ post.content | safe }}</p> </div> </div> <div class="col-md-8 card mb-4 mt-3 "> <div class="card-body"> <!-- comments --> {% with comments.count as total_comments %} <h2>{{ total_comments }} comments</h2> <p> {% endwith %} {% for comment in comments %} </p> <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> {{ comment.name }} <span class=" text-muted font-weight-normal"> {{ comment.created_on }} </span> </p> {{ comment.body | linebreaks }} </div> {% endfor %} </div> </div> <div class="col-md-8 card mb-4 mt-3 "> <div class="card-body"> {% if new_comment %} <div class="alert alert-success" role="alert"> … -
Get the ratio of translation in a Django (or Python) project
Is there a simple way to get the ratio of translated messages in a Django project or by default in a Python project containing .po files? I have seen the Polib library API has a function to do that (https://polib.readthedocs.io/en/latest/api.html#polib.POFile.percent_translated) but it there and easy way to do this with adding this lib and make a script for the CI-check? -
Django migration is getting loose and is creating a separated file to add a field
I'm trying to run Django migration in my project, but something is not working fine, and I couldn't figure out what could be happening. The AuditableModelMixin entity is extended by almost all entities in my project and provides a couple of fields that are used for audit purpose. For all of than, the migrations is runing fine. Although, for the Contract model, the migration is creating the following two separated files: 0001_initial.py class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Contract', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='identifier')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), ('name', models.CharField(max_length=100, unique=True, verbose_name='name')), ('description', models.CharField(blank=True, max_length=1024, null=True, verbose_name='description')), ('created_by', models.ForeignKey(blank=True, db_column='created_by', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='contract_created_by', to=settings.AUTH_USER_MODEL, verbose_name='created by')), ], options={ 'verbose_name': 'contract', 'verbose_name_plural': 'contracts', 'db_table': 'sacv"."contract', }, ), ] 0002_auto_20200524_1912.py (the sequence will change, that's ok) class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contract', '0001_initial'), ('jurisdiction', '0001_initial'), ('state', '0001_initial'), ] operations = [ migrations.AddField( model_name='contract', name='jurisdictions', field=models.ManyToManyField(related_name='contracts', through='jurisdiction.Jurisdiction', to='state.State'), ), migrations.AddField( model_name='contract', name='updated_by', field=models.ForeignKey(blank=True, db_column='updated_by', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='contract_updated_by', to=settings.AUTH_USER_MODEL, verbose_name='updated by'), ), ] I don't know why, it is putting the updated_by into a separated file. It start happening after I have added the ManyToMany relationship … -
I have constants defined in a Django model class. How can I access the constants in a template?
I have a model class with a choice field and its possible values defined as constants, as recommended in https://docs.djangoproject.com/en/3.0/ref/models/fields/#choices class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' YEAR_IN_SCHOOL_CHOICES = [ (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), ] year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) In regular Python code (e.g. in a view), I can easily use the constants like so: if my_student.year_in_school == Student.FRESHMAN: # do something My question is: can I do something like this in a template as well? Something like {% if student.year_in_school == Student.FRESHMAN %} Welcome {% endif %} ... this works if I hard-code the value 'FR' in the template, but that kind of defies the purpose of constants... -
How to create random slug in Django
I have a Django app that will create a contract between two people. The user creates the contract and, upon creation, a random url-safe string is generated using secrets. However, when I create more than one instance of a Contract, the slugs are the same. The only way to get a different randomly generated string is to restart my server. What am I doing wrong? Here's the part that matters in my models.py slug = models.SlugField( default=secrets.token_urlsafe(64), editable=False, blank=False ) Here are the last three Contracts I created. Changing the values of the other fields doesn't change the slug. { "model_email": "POOP@pooop.com", "shoot_location": "Atlanta, GA", "shoot_date": "2020-05-24", "model_name": "", "created_at": "2020-05-24T19:24:20.220845Z", "sent_completed_to_model": null, "sent_completed_to_photographer": null, "photographer": 1, "signed": false, "slug": "Dqyk5-kDzE219_-abRKABETRuOCGOBxzvFVrXZaUGEe8ZLva6i6tdwUYMksSvKJ_BEABV_Vt1H_ttZ6p-yzRyg" }, { "model_email": "POOP@pooop.com", "shoot_location": "Atlanta, GA", "shoot_date": "2020-05-24", "model_name": "", "created_at": "2020-05-24T19:24:21.216218Z", "sent_completed_to_model": null, "sent_completed_to_photographer": null, "photographer": 1, "signed": false, "slug": "Dqyk5-kDzE219_-abRKABETRuOCGOBxzvFVrXZaUGEe8ZLva6i6tdwUYMksSvKJ_BEABV_Vt1H_ttZ6p-yzRyg" }, { "model_email": "POOP@pooop.com", "shoot_location": "Atlanta, GA", "shoot_date": "2020-05-24", "model_name": "", "created_at": "2020-05-24T19:24:22.120845Z", "sent_completed_to_model": null, "sent_completed_to_photographer": null, "photographer": 1, "signed": false, "slug": "Dqyk5-kDzE219_-abRKABETRuOCGOBxzvFVrXZaUGEe8ZLva6i6tdwUYMksSvKJ_BEABV_Vt1H_ttZ6p-yzRyg" } -
How to format tinyMCE within Django-Admin?
I have TinyMCE installed to use it for blog posting which works super fine technically. But the editor itself shows a weird format within the Django/Admin interface as shown below. Is there any way to fix/change the appearence? Config # Tinymce TINYMCE_DEFAULT_CONFIG = { 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, } -
How to attach a html form to Django Form
I do have a form in html and I want to post the data from this form to Django DB. Does there has anyways to do it or I must use the {{form.as_p}} inside the html? The form inside the html: <form method="post"> {% csrf_token %} <div class="row align-items-stretch mb-5"> <div class="col-md-6"> <div class="form-group"> <input class="form-control" id="name" name="name"/> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input class="form-control" id="mail" name="email"/> <p class="help-block text-danger"></p> </div> <div class="form-group mb-md-0"> <input class="form-control" id="phone" name="phone"/> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-6"> <div class="form-group form-group-textarea mb-md-0"> <textarea class="form-control" name="content" id="content"></textarea> <p class="help-block text-danger"></p> </div> </div> </div> <div class="text-center"> <div id="success"></div> <button class="btn btn-primary btn-xl text-uppercase" type="submit">發送</button> </div> </form> views.py. How do I connect the html form to forms.py? def contact(request): form = messageForm(request.POST or None) if request.method == 'POST': form = messageForm(request.POST) if form.is_valid(): form.save() return redirect('/#contact') else: form = messageForm context = { 'form': form, } return render(request, 'contact.html', context) forms.py from django import forms class messageForm(forms.ModelForm): class Meta: model = message fields = ('name', 'mail', 'phone', 'content') -
Django | For some error, different url show same template
I have problems with urls. For example "questions/" shows "def question_list" function well, but "subjects/" url doesn´t show "def subject_list" fucntion. For some reason "subject/" url also show question_list. why? project>urls.py urlpatterns = [ path('admin/', admin.site.urls), path('questions/', include('questions.urls')), path('subjects/', include('questions.urls')), ] APPquestions>urls.py urlpatterns = [ path('', views.question_list, name='questions', ), path('subjects/', views.subject_list, name='subjects', ), ] APPquestions>views.py def question_list(request): preguntas = Pregunta.objects.filter().order_by('id') paginator = Paginator(preguntas,1) page = request.GET.get('page') preguntas = paginator.get_page(page) return render(request, 'questions/questions.html', {'preguntas': preguntas}) def subject_list(request): categorias = Categoria.objects.all() return render(request, 'questions/subjects.html', {'categorias': categorias}) -
Python 3.8-alpine docker compose failing
I have been running an app without docker and have just added in Dockerfile and docker-compose. The issue I am having is that after I successfuly build the app, runserver produces the below error when I run either that or migrate. ➜ app git:(master) sudo docker-compose run app sh -c "python manage.py runserver" Error loading shared library libpython3.8.so.1.0: No such file or directory (needed by /usr/local/bin/python) Error relocating /usr/local/bin/python: Py_BytesMain: symbol not found failed to resize tty, using default size % ➜ app git:(master) sudo docker-compose run app sh -c "python manage.py migrate" Error loading shared library libpython3.8.so.1.0: No such file or directory (needed by /usr/local/bin/python) Error relocating /usr/local/bin/python: Py_BytesMain: symbol not found Dockerfile FROM python:3.8-alpine MAINTAINER realize-sec ENV PYTHONUNBUFFERED 1 COPY requirements.txt /requirements.txt RUN pip3 install -r requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user docker-compose.yml version: "3" services: app: build: context: "" ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" What am I doing wrong that is causing this? When I run without docker using python3 manage.py runserver it works fine. -
Render errors while trying to load Django templates
I'm receiving the error "render() got an unexpected keyword argument 'renderer'" while I try to run my Django web app. When I remove the error shown, the app runs bu without some fields and looks like this. When I take a look at the forms.py file, I see that the code doesn't have any errors. The rest of the file can be seen here. I can't seem to find where the problem is as I've only started with Django as a way of learning python. Can anyone point to me where the problem is and help me get a solution to it? Thank you. -
How to "link" already uploaded images to ImageField in Django?
I have models like: class Symbol(models.Model): slug = models.SlugField(unique=True) #uniqe name = models.CharField(max_length=255, unique=True) imgslug = models.CharField(unique=False, max_length=255, blank=True) #uniqe def __str__(self): return self.name class Platform(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class PlatformImages(models.Model): symbol_id = models.ForeignKey('Symbol', on_delete=models.CASCADE,) platform_id = models.ForeignKey('Platform', on_delete=models.PROTECT,) class Meta: indexes = [ models.Index(fields=['symbol_id', 'symbol_id']), ] constraints = [ models.UniqueConstraint(fields=['symbol_id', 'platform_id'], name='unique_symbol_img_per_platform') ] def __str__(self): return str(self.platform_id) def get_platform_name(self): return self.platform_id I have folders per platform in media folder like: media/apple/, media/google/, media/twitter/ ,etc. Inside each folder there are ~1000-3000 images, named as "imgslug" for almost each Symbol. I had uploaded them in a batch. And I use it In template to show all available images for symbol per platform: {% for platform in platforms %} <img src="{{ MEDIA_PREFIX }}{{platform}}/{{symbol.imgslug}}" > <h2 class="">{{platform|title}}</h2> {% endfor %} The problem is that now I need to edit/upload new images via Admin tool. I added this code to edit mapping of image to Platform: class PlatformInline(admin.TabularInline): model = PlatformImages class SymbolAdmin(admin.ModelAdmin): inlines = [ PlatformInline, ] Now I think to add ImageField to PlatformImages Model, but I need: to save each image per unique platform for symbol in corresponding folder to add there already uploaded files And … -
Setting up a search function in my Django app
Quick question: I made a search bar in my Django app. It works if I type in first or last name. But when I try AND & it doesn't work. Here's what I have: def names(request): all_names = name.objects.all search_term = "" if 'search' in request.GET: search_term = request.GET['search'] all_name = name.objects.filter( Q(first__startswith=search_term) | Q(last__startswith=search_term) return render(request, "about.html", {'all_names': all_names, 'search_term': search_term}) This works as far as OR is concerned but when I slide the & in place of the | it looses functionality. I'm stumped. According to the Django docs, & should automatically include both. I just want to be able to type in both first and last name in the search bar. -
How to i grab data inside my database without inserting?
I am very new to django and I am just messing around to get the hang of it. When I run my POST request, my data inserts the data to database then gets the data column that was inserted. However, I am wondering, why it is inserting and only grabbing the data column that was inserted. Shouldn't my code grab all the data from Users and not insert the data? I know I can use GET request instead of POST but still, I am wondering why it is functioning like this and how I can fix my code? Thanks #qssgg Viewset class UsersViewSet(viewsets.ModelViewSet): serializer_class = UsersSerializer queryset = Users.objects.all() -
Django User Follower system with accept & reject option
Hello guys I have a simple user follow system, I want it to have an accept/reject option as we see with instagram private accounts. How to implement such a system. I can work on it if anyone can help me with some hints to start with. Any leads would be appreciated. I will share the model I have now here. models. class Contact(models.Model): user_from = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) #USER_FROM IS THE ONE WHO IS FOLLOWING AND USER_TO IS ONE BEING FOLLOWED class Meta: ordering = ('-created',) def __str__(self): return f'{self.user_from} follows {self.user_to}' following = models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False) #adding the above field to User Model class user_model = get_user_model() user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) views. @login_required def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') store = Store.objects.get(user= request.user) #called to remove store manager if unfollowed. if user_id and action: try: user = Account.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create(user_from=request.user, user_to=user) create_action(request.user, 'started following', user) else: Contact.objects.filter(user_from=request.user, user_to=user).delete() #to remove from family filter when unfollowed request.user.profile.family.remove(user) store.store_managers.remove(user) #remove store manager return JsonResponse({'status':'ok'}) except User.DoesNotExist: return JsonResponse({'status':'error'}) return JsonResponse({'status':'error'}) Thanks in advance! -
Is Model.clean() being called before form_valid()?
I'm new to Django and I'm trying to make use of the CreateView CBV. I have the following Model: class Child(models.Model): # one of user and session must be populated user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, 'children', null=True, blank=True) session = models.ForeignKey(Session, models.CASCADE, 'children', null=True, blank=True) ... def clean(self): super().clean() if (self.user is None) and (self.session is None): raise ValidationError('Either user or session must be populated.') Then I have the following CreateView: class ChildCreateView(CreateView): model = Child fields = ['name','gender','age'] ... def form_valid(self, form): form.instance.user = self.request.user form.instance.session = self.request.session return super(ChildCreateView, self).form_valid(form) However, when I navigate to the view in my browser and try to create a new Child using the form, I see "Either user or session must be populated" after pressing submit. Based on what I've read in the Django documentation it seems that the right place to assign Model.user is in ChildCreateView.form_valid(), but I don't seem to be getting the chance to do so. Instead, ChildCreateView.form_invalid() is getting called, evident from a print() statement I put in there. What am I missing here? I thought Form.save() gets called in ChildCreateView.form_valid(), so is Child.clean() getting called before ChildCreateView.form_valid()? Thanks very much! -
inconsistent use of tabs python
I am getting the following error: How can I fix it? File "/Users/rjeudy/PycharmProjects/virtualenv/virtualenv/src/products/forms.py", line 35 def clean_title(self, *args, **kwargs): ^ TabError: inconsistent use of tabs and spaces in indentation def clean_title(self, *args, **kwargs): title = self.cleaned_data.get("title") if "CFE" in title: return title -
Need help setting Android Client up to authenticate with Django using Google oauth token
I'm quite new to Django framework and came up with a problem regarding token authentification from an Android end point. What I'm trying to do: Retrieve an OAuth token from Google Auth in Android Client (which I managed to do following this guide https://developers.google.com/identity/sign-in/android/start-integrating) Authenticate to my Django Rest API. Create an account if it's the first time the user logs in, and retrieve the user instance using this token I require the user model in Django to hold a few other attributes other than default. I'm currently doing this by extending AbstractUser and adding AUTH_USER_MODEL = 'path.to.model.User in app's settings.py What I don't understand How to create (if it's their first time) or retrieve the user instance from Django using the token. Since I don't sign in with username and password, how to set the user primary key to be their email. What I don't want To send user credentials such as username and password from Android to Django to get an Oauth token from server since I only require social app auth. Thanks in advance! -
Django: Couldn't import JavaScript files from static directory. (Jinja2)
I just started Django and I'm trying to import JavaScript Files from static directory. So basically I was working on a Flask project for some time, so to import javascript file I was always using - {{ url_for('.static', filename='js/js_file1.js' }}. Now I realized that I need to use other methods as - {% static 'main/js/js_file1.js' %}. So after some time, I was able to import my css files with - <link rel="stylesheet" href="{% static 'main/css/styles.css' %}">, they are in static/main/css/files..., although my js files are in static/main/js/files.... But for some reason, the JavaScript files won't import themselves. I'm importing them with - <link rel="application/javascript" href="{% static 'main/js/bootstrap.min.js' %}">. Here's the network log from Developer console, as I can see there are no JS files on their way to import themselves. And here's the Server Log from the running server on cmd. Developer Console Log. My settings.py file has this static_url, which I guess specifies the static folder. # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' My whole HTML File. -
RuntimeError: Model class django_embed.models.SeaSurfaceTemperature doesn't declare an explicit app_label and isn't in a
I get this error when I try to import my model SeaSurfaceTemperature into views.py (line 16). I’ve researched the issue but none of the proposed fixes works for me. Here I my repo: https://github.com/theresemoreau/django_bokeh_test I would so appreciate the help with fixing this issue. I’m completely new to django so please bare with me. I’m trying to learn to create a web app displaying an interactive bokeh visualization. Everything works perfectly when I import data from bokeh.sampledata (i.e. out-comment line 16). However, what I’m really interested in is importing data from a postgresql db via django model, so I downloaded the data set and put it into the table SeaSurfaceTemperature under the database teledataskandalen. -
Django why my static JS files not loading
I have a django project I am working on, and I am pretty new to Django and Python in general. I have created my base.html as the following: {% load adminlte_helpers i18n %} {% load static %}<!DOCTYPE html> <html> <head> {% block stylesheets %} {% include 'adminlte/lib/_styles.html' %} {% endblock %} {% block body %} .... {% endblock body %} {% block javascript %} {% include 'adminlte/lib/_scripts.html' %} {% endblock %} {% block extra_js %} {% endblock %} </body> </html> After that I have created my _scripts.html file as the following: {% load static %} {% block scripts %} <script src="{% static 'admin-lte/plugins/jquery/jquery.min.js' %}"></script> <script src="{% static 'admin-lte/plugins/jquery-ui/jquery-ui.min.js' %}"></script> <script src="{% static 'admin-lte/plugins/chart.js/Chart.min.js' %}"></script> <script src="{% static 'admin-lte/plugins/bootstrap/js/bootstrap.bundle.min.js' %} "></script> {% block datatable_js %}{% endblock %} {% endblock %} Now I want to to add in a new html file named example.html a chart created with charts.js. Now I have created it and added in the example.html. But If I try to created a new js file (named graph.js) in my static folder but if I load it in my template does not work. In which part of my code I have to insert <script src="{% static "grafici/graph.js" %}"></script> to … -
Should the data from API be saved to the database or just call API everytime when data is needed for a website
Please assume I have no experience in developing the structure of websites. I am currently working on a website that displays data fetched from an API. (I use Django and python for the web app) I want to display the current Covid-19 data and analyze the trend in graphs and charts. I am able to grab the data from the API, but question is for a site like that needs an update on the numbers on a daily basis, what is the best practice for retrieving data. Should I be saving the api data to my database for easier access or should I just call the API everytime when the web page is visited (which is already a necessity due to the day to day update) and process data? (Performance wise or easily of processing data.) I would appreciate if anyone would share their experience. -
Flask subdomain is rediecting to main domain in nginx - AWS
I have subdomains in my flask web app which i wanna host in aws using nginx and gunicorn server { listen 80; server_name domain.com *.domain.com; location /static { alias /home/ubuntu/flaskblog/static; } location / { proxy_pass http://localhost:8000; include /etc/nginx/proxy_params; proxy_redirect off; } } My flaskblog contains flask blueprints which can access admin.domain.com dept.domain.com and so on .... locally . In my localhost i used to add these paths in /etc/hosts 127.0.0.1 admin.domain.com 127.0.0.1 dept.domain.com ..... But unable to process data in nginx I am searching everywhere but didn't find any solution to access my subdomain , when i use subdomain.domain.com it always redirect to domain.com Can anyone help me out Thanks in Advance -
I Can Create a User from DjangoAdmin Without Providing REQUIRED_FIELDS
I made the 'name' and 'surname' required in my Account class and when I run manage.py createsuperuser it does not allow me to create user without providing a name and surname string But somehow when I login from django admin, I can create Account instance without giving a name or surname. But I can not edit it without providing a name and surname string. Why django admin allows me to create Account instance without a required field? When I try to edit the object and save it, django admin doesn't allow me to do so without providing name and surname. I use python version 3.8 and Django version 3.0 https://i.stack.imgur.com/L4ayu.jpg https://i.stack.imgur.com/OI0ms.jpg My Account model: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): """creates and saves new user""" def create_user(self, email, password, name, surname, **extra_fields): if not email: raise ValueError('Users must have an email adress.') if not password: raise ValueError('Users must have an password.') if not name: raise ValueError('Users must have an name.') if not surname: raise ValueError('Users must have an surname.') user = self.model( email = self.normalize_email(email), name = name, surname = surname ) user.set_password(password) #set_password function is used to store the password encripted user.save(using=self._db) return user def create_superuser(self, email, … -
multiple values for argument on_delete
class Product_Diverse(models.Model): name = models.CharField(max_length=100, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_order = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(Product_main, Product_Diverse, Product_Teknikprylar, Product_Verktyg, Product_Maskiner, Product_Guldfynd, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) Hey! when i run this code I gat an error wich looks like the text below and I acctuly have no clue on how to fix it becuse im a newbie, someone on here must know how to fix this, was following a tutorial on youtbe and started makeing some of my own changes. thanks in advance! File "C:\Users\kristian\webdevelopment\websida\ecommerce\store\models.py", line 131, in OrderItem product = models.ForeignKey(Product_main, Product_Diverse, Product_Teknikprylar, Product_Verktyg, Product_Maskiner, Product_Guldfynd, on_delete=models.SET_NULL, blank=True, null=True) TypeError: init() got multiple values for argument 'on_delete' -
running celery tasks and celery beat in ECS with Django
I'm using ECS for the first time. I have dockerized my Django 2.2 application and using ECS and uwsgi to run the Django application in production. While in the development environment, I had to run three commands to run Django server, celery and celery beat python manage.py runserver celery -A qcg worker -l info celery beat -A qcg worker -l info Where qcg is my application. My Dockerfile has following uwsgi configuration EXPOSE 8000 ENV UWSGI_WSGI_FILE=qcg/wsgi.py ENV UWSGI_HTTP=:8000 UWSGI_MASTER=1 UWSGI_HTTP_AUTO_CHUNKED=1 UWSGI_HTTP_KEEPALIVE=1 UWSGI_LAZY_APPS=1 UWSGI_WSGI_ENV_BEHAVIOR=holy ENV UWSGI_WORKERS=2 UWSGI_THREADS=4 ENV UWSGI_STATIC_MAP="/static/=/static_cdn/static_root/" UWSGI_STATIC_EXPIRES_URI="/static/.*\.[a-f0-9]{12,}\.(css|js|png|jpg|jpeg|gif|ico|woff|ttf|otf|svg|scss|map|txt) 315360000" USER ${APP_USER}:${APP_USER} ENTRYPOINT ["/app/scripts/docker/entrypoint.sh"] The entrypoint.sh file has exec "$@" I have created the ECS task definition and in the container's command input, I have uwsgi --show-config This starts the uwsgi server. Now I'm running 1 EC2 instance in the cluster and running one service with two instances of the task definition. I couldn't figure out how to run the celery task and celery beat in my application. Do I need to create separate tasks for running celery and celery-beat?