Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve integrity error in my Django project
I have a form that an admin uses to register student when he logs into the website. I extended the Django User model to accommodate things like gender, phone, profile_pic, time. Each time I fill the fields I get this error UNIQUE constraint failed: backend_extenduser.user_id on the browser when I scroll down a little bit I see this The above exception (UNIQUE constraint failed: backend_extenduser.user_id) was the direct cause of the following exception I want to know what is causing this? And how I can solve this I have another project that has the same code base, this project works fine but this very project I am working on is throwing error. Below are my codes on models.py class ExtendUser(models.Model): MALE = 'ML' FEMALE = 'FM' GENDER = [ (MALE, 'Male'), (FEMALE, 'Female'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=15) profile_pic = models.ImageField(verbose_name='Profile Picture', blank=True, null=True, upload_to='backend_uploads') gender = models.CharField(max_length=2, choices=GENDER, default=MALE, blank=False, null=True) time = models.DateTimeField(default=timezone.now) def __str__(self): return self.user.username I want to reduce my forms.py to show only the code that I adds addtional field to the Django User Model class ExtendUserForm(forms.ModelForm): class Meta(): MALE = 'ML' FEMALE = 'FM' GENDER = [ (MALE, 'Male'), (FEMALE, 'Female'), … -
how to reset table's id(Django)
#leader_board <div class="container" id="content"> <div class="row"> <table class="table table-striped" style="text-align: center; border:1px solid #dddddd;"> <thead> <tr> <th class="ng" style="background-color: #eeeeee;text-align: center;">#</th> <th class="ng" style="background-color: #eeeeee;text-align: center;">user</th> <th class="ng" style="background-color: #eeeeee;text-align: center;">submission_date</th> <th class="ng" style="background-color: #eeeeee;text-align: center;">rank</th> </tr> </thead> <tbody> {% for submission in submissions.all %} <tr> <td class="ng">{{submission.id}}</td> <td class="ng">{{submission.user_name}}</td> <td class="ng">{{submission.submission_time}}</td> <td class="ng">{{submission.user_score}}</td> </tr> {% endfor %} </tbody> </table> <a href="{% url 'sub_page' %}" class="btn btn-dark pull-right">submit</a> </div> class Submission(models.Model): user_name = models.CharField(max_length=100, default = 'parrotadmin') user_ranking = models.FloatField(default=0) submission_file = models.FileField(upload_to='documents/', default=None) submission_status = models.CharField(max_length=50) submission_time = models.DateTimeField('Submission Date', auto_now_add=True) class Meta: verbose_name = 'submission' verbose_name_plural = 'submissions' db_table = 'parrot_con' ordering = ('-user_score',) #output example(mine) ------------------------ # user time score 3 # ###### 0.98 1 # ###### 0.88 2 # ###### 0.78 ------------------------ #what I want 1 # ###### 0.98 2 # ###### 0.88 3 # ###### 0.78 I'm trying to make leader-board for my study group with django. What I'm struggling with is resetting index of my table to show user's rank plus) If there's any master of django, I have a question I have a code made with pandas and sklearn accuracy score. If I want to open uploaded csv file and get score, which … -
Pandas to_csv() throwing 'ascii' encoding exception even when set to encoding='utf-8'
I've got a file with some utf-8 characters. Loaded it into a dataframe (with encoding explicitly set to utf-8) and now trying to write it out to a csv. I keep getting a UnicodeEncodeError, and I'm not sure why. I've set encoding='utf-8' (also tried encoding='utf8') and I still get it, with reference to 'ascii' codec. One clue is I don't get the issue when testing this on a Windows machine, but I do get it on an Ubuntu machine. I've tried upgrading pandas from 0.25 -> 1.0 and it makes no difference. Note also that this is being used within Django. df.to_csv(f, index=False, line_terminator='\\n', encoding='utf-8') File "/home/webapp/.virtualenvs/django/lib/python3.6/site-packages/pandas/core/generic.py", line 3203, in to_csv formatter.save() File "/home/webapp/.virtualenvs/django/lib/python3.6/site-packages/pandas/io/formats/csvs.py", line 204, in save self._save() File "/home/webapp/.virtualenvs/django/lib/python3.6/site-packages/pandas/io/formats/csvs.py", line 323, in _save self._save_chunk(start_i, end_i) File "/home/webapp/.virtualenvs/django/lib/python3.6/site-packages/pandas/io/formats/csvs.py", line 354, in _save_chunk libwriters.write_csv_rows(self.data, ix, self.nlevels, self.cols, self.writer) File "pandas/_libs/writers.pyx", line 65, in pandas._libs.writers.write_csv_rows UnicodeEncodeError: 'ascii' codec can't encode character '\\xc7' in position 67: ordinal not in range(128) -
Django: Is there any way to make unique object's relationship?
We have many-to-one and many-to-many. Making a little logistic app, I try to imagine, how to write something like warehouse/stockpile? For example, some kind of tool or equipment today is used by John Smith or any other ~smith. What is the best way to show that equipment is not used by anybody, just lying in the warehouse, except giving it the warehouse' keeper's data as the ForeignKey? This kind of relationship was already rejected by my client, can't imagine any others. -
Start Django in Docker with monit
I'm having a Docker with testing-environment (Fedora) with a Django and an Apache. The Apache is for production, but the Django will live on for testing and development. Both services are started with monit. As both are using different ports it works fine if they are regularly started. Just monit doesn't seem to start the Django correctly: monitrc check process django-admin with pidfile /var/run/django-admin/django-admin.pid start program = "/usr/local/bin/django-admin runserver 0.0.0.0:9900 --pythonpath=/home/djangohome --settings=DjangoMoP.settings" check process httpd with pidfile /var/run/httpd/httpd.pid start program = "/usr/sbin/httpd -D --FOREGROUND" I'm starting monit -I -vv and get these logs: web_1 | Adding 'allow localhost' -- host resolved to [::ffff:127.0.0.1] web_1 | Adding 'allow localhost' -- host resolved to [::1] web_1 | Adding credentials for user 'admin' web_1 | Adding 'allow 1xx.xxx.1.xxx' -- host resolved to [::ffff:1xx.xxx.1.xxx] web_1 | Runtime constants: web_1 | Control file = /etc/monitrc web_1 | Log file = syslog web_1 | Pid file = /run/monit.pid web_1 | Id file = /root/.monit.id web_1 | State file = /root/.monit.state web_1 | Debug = True web_1 | Log = True web_1 | Use syslog = True web_1 | Is Daemon = True web_1 | Use process engine = True web_1 | Limits = { web_1 | … -
Django : How can I make CheckboxSelectMultiple field save default
I'd like to make if payer is not in the dutch_payer, I'd like to same payer name user checked in dutch_payer. So payer is always checked in dutch_payer as a default. how can I make it? class UpdateMoneylogForm(forms.ModelForm): class Meta: model = models.Moneylog fields = ( "pay_day", "payer", "dutch_payer", "price", "category", "memo", ) widgets = { "pay_day": forms.DateTimeInput(attrs={"style": "width:100%"}), "dutch_payer": forms.CheckboxSelectMultiple, "memo": forms.Textarea(attrs={"rows": 3, "style": "width:100%"}) } def save(self, *args, **kwargs): payer = self.cleaned_data.get("payer") dutch_payer = self.cleaned_data.get( "dutch_payer").filter(name=payer) if dutch_payer.count()==0: # some code in here moneylog = super().save(commit=False) return moneylog -
Application deployment in pythonanywhere
Right now am only trying to work on the console of pythonanywhere I tried to put this following command but it would display "syntax errors:invalid syntax " -: "pa_autoconfigure_django.py --python=3.8.0 https://github.com//my-first-blog.git" Note that I have already installed pythonanywhere using the pip. What do I do? I notice that PythonAnywhere is based on Linux. -
Django - how to generate thumbnails without killing the save method?
I want to save a thumbnail and a higher quality scaled image from a user upload (take a cover of a post object for example). Now im facing the issue that each time i use the save Method (which is quite often) my images are getting re-generated/re-saved which again is kind of stupid and useless to me. models.py ... postcover = models.ImageField( verbose_name="Post Cover", blank=True, null=True, ) postcover_tn = models.ImageField( verbose_name="Post Cover Thumbnail", blank=True, null=True, ) ... def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) if self.postcover: if os.path.exists(self.postcover.path): image = Image.open(self.postcover) outputIoStream = BytesIO() baseheight = 500 hpercent = baseheight / image.size[1] wsize = int(image.size[0] * hpercent) imageTemproaryResized = image.resize((wsize, baseheight)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.postcover.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) image = Image.open(self.postcover) outputIoStream = BytesIO() baseheight = 100 hpercent = baseheight / image.size[1] wsize = int(image.size[0] * hpercent) imageTemproaryResized = image.resize((wsize, baseheight)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.postcover_tn = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.postcover.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) elif self.postcover_tn: self.postcover_tn.delete() super(Post, self).save(*args, **kwargs) it would also be very nice to know how i can clear the InMemoryUploadedFile after postcover and postcover_tn have been created. -
Django renaming class casued AttributeError: 'str' object has no attribute '_meta'
How can I solve this issue, I renamed a through Model class and now getting the following error when trying to migrate: (django_env) UKC02TQH6UHV22:pcc_django rki23$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, microblog, project_portal, sessions, url_tree Running migrations: Applying project_portal.0012_auto_20200205_1241...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/Users/rki23/opt/anaconda3/envs/django_env/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 524, in alter_field not new_field.remote_field.through._meta.auto_created): AttributeError: 'str' object has no attribute '_meta' (django_env) UKC02TQH6UHV22:pcc_django rki23$ What do I need to do to fix this please? -
Django restful pagination
I want a code for RESTful API pagination for django without using REST Framework? I know this code is wrong but want to modify same code that will run properly... enter code here @csrf_exempt def pagination(request,pageNo): if request.method == "GET": get_all = Item.objects.all() if pageNo == 1: pageNo=0 count=0 for i in range(3): try: if get_all.get(id=i+1) is not None: count=count+1 else: break except: pass get_spec=get_all[pageNo:count] print("page_no"['pageNo']) return JsonResponse({ "pageNo":get_spec.pageNo }) else: count=0 i=(pageNo-1)*3 for i in range(pageNo*3): try: if get_all.get(id=i+1) is not None: count=i+1 else: break except: pass get_spec=get_all[(pageNo-1)*3:count] return JsonResponse({ "pageNo":get_spec.pageNo }) -
unable to change form field label in django
I'm trying to change the label name of a form field in django, but it won't change. I've changed all instances of the word throughout my code, but still it remains what it originally was. Do I have to delete the form and rewrite it or is there another way to force django to reflect the code? -
How to PyTest, Mixer, Django, OneToOneField
As suggested by most Django tutorials, I made my own User model via AbstractUser and also created a Profile-model with further details like a bio which is linked to User via a OneToOneField. Now I'm starting to write tests and I am not sure how to reference the Profile Model from within there. test_models.py import pytest from mixer.backend.django import mixer pytestmark = pytest.mark.django_db class TestUsers: def test_user(self): obj = mixer.blend('player.User') assert obj.pk == 1, 'Should save one instance of a user' assert obj.Profile.bio is not None, 'There should be at least default bio' Which get's me an `AttributeError: 'User' object has no attribute 'Profile' models.py class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) bio = models.CharField(max_length=130, default='No bio written yet.') @receiver(post_save, sender=get_user_model()) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=get_user_model()) def save_user_profile(sender, instance, **kwargs): instance.profile.save() How do I reference the profile that should have been created via the signals in models.py for testing? -
MDBootstrap for Django Form Fields
Has anyone had any success incorporating MDBootstrap classes into their Django forms? I have MDBootstrap working fine in my Django project, but since I am having django render my form fields I can't figure out how I could use the MDBootstrap form component styling. Essentially if I do this it comes up with the bootstrap styling: <input type="text" id="textInput" class="form-control mb-4" placeholder="First Name"> But since I'm rendering my forms fields like this - I can't figure out how to achieve the same cosmetic result: {{form.firstname}} -
CSSParseError when adding boostrap to an html file in Django and turn it into a pdf
Im trying to make a simple report in my Django app, and download it into a pdf Im using xhtml2pdf to do so, when I build my html the page looks fine on my browser, but when turn in into a pdf Im getting this error Selector Pseudo Function closing ')' not found:: (':not(', '[controls]) {\n disp') I tried to isolate the issue and noticed everything works fine until I paste the bootstrap css code into my html, Im currenty Bootstrap v3.3.4 This is my render_to_pdf function def render_to_pdf(template_src, context_dict={}): """Function to render a django template into a pdf """ template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None and this is were I make the actual pdf def print_pdf(request): policy = Policy.objects.get(pk=20) context = { 'policy' : policy } pdf = render_to_pdf('pdfs/payment-control.html', context) return HttpResponse(pdf, content_type='application/pdf') I hope you guys can help me -
how to get data from legacy database in Django 3 app?
I am developing a new application using django 3 and a new postgresql database 9.5+ (django 3 requires 9.5 or more). But there is data that is stored in the legacy postgresl database 8.4. I do not need all the data, but only a part (some fields of some tables). For example, in the old database, data is distributed among related tables using foreign keys. But I need to combine some data into one table in a new database, and not store foreign keys. How to transfer data once for development? Also, the data in the old database changes and I need to periodically update this data in the new database (every few minutes or hours or even days, depending on how much it will be resource-consuming, there is no need for frequent updates). Ideally update only modified data. How to do it? What features does the database have? Or is it better to use Django for these purposes? Or server / os? Or directly access the old database in each request (dblink?) And not transfer data? How slow will it be? -
How to align form input
I'm going crazy trying to align a form with Django and Bulma. Here is the problem, the input shows misaligned: That is what happens when I try to set the alignment to center. If I align left the input text shows properly, but not in the center of the screen as I want it. This is the template code. Display:block was just a try to fix it but makes no difference at all. {% for field in wizard.form %} <div class="field has-text-centered"> {% for error in field.errors %} <div><p class="help is-danger">{{ error }}</p></div> {% endfor %} <label class="label" style="display:block;">{{ field.label_tag }}</label> <div class="control has-text-centered" style="display:block;">{{ field }}</div> {% if field.help_text %} <p class="help is-danger">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} Thanks a lot for the help, I've been struggling for 1'5 hour with something that seems so relatively simple! -
How can I display different results onto separate templates from one model in Django, using class based views?
I have one model: class Product(models.Model): slug = models.SlugField(unique=True) image = models.ImageField(upload_to='media') title = models.CharField(max_length=150) description = models.TextField() short_description = models.CharField(max_length=300) price = models.DecimalField(max_digits=5, decimal_places=2) discount_price = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) stock_quantity = models.PositiveIntegerField(default=10) in_stock = models.BooleanField(default=True) on_sale = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now_add=True, blank=True) main_category = models.CharField(default='FW', choices=CATEGORY_CHOICES, max_length=2) additional_category = models.CharField(choices=CATEGORY_CHOICES, max_length=2, blank=True, null=True) brand = models.CharField(choices=CATEGORY_CHOICES, max_length=2, blank=True, null=True) size = models.CharField(max_length=2, choices=CATEGORY_CHOICES, default='M', blank=True, null=True) def __str__(self): return self.title Within this model will be various types of products for example, clothes and books. These will be defined by the main_category and additional_category fields within the model. If the product being entered into the database is a piece of clothing I will enter values for size and brand. For books, these will obviously be blank. However, if the product is a piece of clothing, I have clothing for women, clothing for men and clothing for children. I will be able to define these by selecting 'for women' in the main_category field. In my templates, I would like to dynamically display a page that shows all clothes, one that displays 'clothes for women', another page that shows 'clothes for men' etc etc. And then a page that displays all … -
Decode utf-8 to unicode in Django
How can we decode from utf-8 to html hex code so we can display the special character. Are there any plugins that handle such or are there any pipes that we can use in Django to render this instances. input = 'with a \xce\xb2-ionone' encode_utf = input.encode('utf-8') decode_utf = encode_utf.decode() //output: 'with a β-ionone' EXPECTED OUTPUT = 'with a β-ionone' From the utf-8 code, I expected to have the β tag instead of the plain UTF-8 equivalent of β which is β. -
Best practice of data file location for wsgi.py and manage.py
I have django project. I sometimes need to put file in somewhere and use from python manage.py XXX command and from apache server with wsgi.py However these two are located different directory like this below. |- mysite - wsgi.py |- manage.py |- myitem.txt I want to open myitem.txt from both manage.py and wsgi.py. open(myitem.txt) works on manage.py but not on the script accessed by wsgi.py. How should I do??or is it bad idea to put myitem.txt here?? -
Selecting a radio button using Django ModelChoiceField gives an error message "value must be a float"
I am trying to create a RadioSelect widget using ModelChoiceField in Django, but my form is not valid. When I print out form.errors, I get the error that the choice selected is the object, rather than the float that is expected for that field. Here is the relevant model: class Observation(models.Model): obsid = models.AutoField(primary_key=True) object = models.ForeignKey(Supernova,on_delete=models.PROTECT, editable=False) mu = models.FloatField(null=True,default=None) zhel = models.FloatField(null=True,default=None) bestmu = models.IntegerField(null=True,default=1) bestz = models.IntegerField(null=True,default=1) date = models.DateField(null=True) date_change_z = models.DateField(null=True) date_change_mu = models.DateField(null=True) Here is the relevant form: class ChangeBestMu(forms.ModelForm): mu = forms.ModelChoiceField(widget=forms.RadioSelect(), queryset=None, empty_label=None, label = 'Select new best value from all known values of mu:') def __init__(self, *args, **kwargs): self.snid = kwargs.pop("snid") super(ChangeBestMu, self).__init__(*args, **kwargs) self.fields['mu'].queryset = Observation.objects.values('mu').filter(object_id=self.snid) self.fields['mu'].label_from_instance = lambda obj: "Mu: {mu}\tDate Changed: {dm}".format(mu=obj.mu, dm=obj.date_change_mu) class Meta: model = Observation fields = ('mu',) Here is the relevant view: def changemu(request, snid): if request.method == 'POST': form = ChangeBestMu(data=request.POST, snid=snid) if form.is_valid(): data = form.cleaned_data.get('mu', None) return HttpResponseRedirect('/Best Mu Changed/') else: return render(request, 'supernova/mu.html', {'data': form.errors}) else: form = ChangeBestMu(snid=snid) snid = int(snid) return render(request, 'supernova/changemu.html', {'form': form, 'snid': snid}) Here is my template: {% extends "base.html" %} {% block title %}Change Best Value of Mu{% endblock %} {% block content … -
problems with get_absolute_url()
Please, I need your help. I can't return urls from model to template. I think that problem in method "get_absolute_url". That's error that I get: NoReverseMatch at / Reverse for 'product_list' with arguments '('saws',)' not found. 1 pattern(s) tried: ['$'] Code is: #models class Category(models.Model): name = models.CharField(verbose_name='Category', max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True, unique=True) ... def get_absolute_url(self): return reverse('core:product_list', args=[self.slug]) urls.py app_name = 'core' urlpatterns = [ path('', views.ProductView.as_view(), name='product_list'),] views.py class ProductView(generic.ListView): queryset = Product.objects.filter(available=True) categories = Category.objects.all() def get_context_data(self, **kwargs): context = super(ProductView, self).get_context_data(**kwargs) ... context['categories'] = self.categories return context html <li {% if not category %}class="selected"{% endif %}> <a href="{{ categories.get_absolute_url }}"All</a> </li> {% for c in categories %} <a href="{{ c.get_absolute_url }}">{{ c.name }}</a> <!--if delete 'c.get_absolute_url', except escape--> {% endfor %} -
How to hide filefield url in django Admin
Create A image File Field in my model hide image url or not clickable image name url Currently: eeee_2020-02-05T100811.271582.txt please refer this link -
How to associate user to a post request in Django drf
I have the following : I am working with DRF, based JWT token. I want to associate an experiment with a USER, i.e when a post request is arriving I want to be able to save that post request with the Foreginkey it needed for the author by the user whom sent the request. The POST request is always authenticated and never anonymous, i.e request.user is always exist ( I can see it when debugging) I tried to add the following def create(self, request, **kwargs): request.data["author"] = request.user serializer = ExperimentsSerializers(data=request.data) if serializer.is_valid(): serializer.save() return.... But is_valid return always False ( the only time ts was true, was when I took out the author from the ExperimentsSerializers fields.... will be happy for any leads.... my code attached below Model.py: class User(AbstractUser): pass def __str__(self): return self.username class Experiments(models.Model): name = models.CharField(max_length=40) time = models.DateTimeField(default=timezone.now) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) View.py: filter_backends = [DjangoFilterBackend, filters.OrderingFilter] serializer_class = ExperimentsSerializers queryset = Experiments.objects.all() filterset_fields = '__all__' permission_classes = (permissions.IsAuthenticated,) serializers.py class ExperimentsSerializers(serializers.ModelSerializer): class Meta: model = models.Experiments fields = '__all__' -
Static files couldnt applied in Django
I'm new in Django and i see course in youtube I try to include bootstrap\css files into HTML template and i created a static file into the app like the photo Also i checked the file(second\ urls.py) and in it the code ''' STATIC_URL = '/static/' INSTALLED_APPS = [ 'accounts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ''' And in login.html there is this link ''' {% load static%} <link rel="=stylesheet" type="text/css" href="{% static 'accounts/style.css' %}"> ''' I applied other way like adding this second\setting.py STATICFILES_DIRS = [ os.path.join(BASE_DIR,"accounts/static"), 'accounts/static/' ] In the terminal there is warning but i think it isnt affect WARNINGS: ?: (2_0.W001) Your URL pattern '^account/' has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). -
compare value of form in view django
View.py class Register(TemplateView): template_name = 'registration.html' def get(self, request, *args, **kwargs): form = CreateForm() return render(request, self.template_name, {'form': form}) @staticmethod def post(request): try: data = request.POST.get user = User( first_name=data('first_name'), last_name=data('last_name'), username=data('username').strip(), email=data('email'), ) user.set_password(data('password').strip()) user.save() request.session["user_id"] = user.id return HttpResponse(' Save successfully ') except Exception as c: return HttpResponse("Failed : {}".format(c), 500) Form.py role_choice= (("Customer", "Customer"), ("Employee", "Employee")) class CreateForm(forms.Form): first_name = forms.CharField(label="Enter Your First Name", max_length=30, required=True) last_name = forms.CharField(label="Enter Your Last Name", max_length=30, required=True) username = forms.CharField(required=True, widget=forms.TextInput()) email = forms.CharField(required=True, widget=forms.TextInput()) password = forms.CharField(required=True, widget=forms.PasswordInput()) role = forms.ChoiceField(choices=role_choice, widget=forms.RadioSelect()) class Customer(forms.Form): contact = forms.IntegerField(label="Enter your contact number", required=True, ) amount = forms.IntegerField(required=True, min_value=500) type = forms.ChoiceField(choices=choice) Model.py class Customers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) contact = models.BigIntegerField() amount = models.BigIntegerField() type = models.CharField(max_length=1) Template {% extends "home.html" %} {% load crispy_forms_tags %} {% block title %}Create Account{% endblock %} {% block content %} <div> {% csrf_token %} {{ form|crispy }} <button type="submit">Submit</button><br> </div> {% endblock %} After the registration when user select customer option after sumbit the form i go to customer page if user select employee option he/she go to employee page but i don't know how to do this