Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django two web pages have seperate apps or a single app
I am new in Django. Can anyone please help me. I have created 2 webpages 1 is for registration and 2nd is for login. Now i can i use both forms in simgle app or two seperate apps for both the pages. And also tell me about models.py page in this problem. Thank you -
How I can solve this python problem?[django]
Why cannot migrate. What the problem it shows type error. Here is the models from django.db import models # Create your models here. class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="" ) subcategory = models.CharField(max_length=50, default="" ) price = models.IntegerField(default=0) desc = models.CharField(max_length=300) pub_date = models.DateField() image = models.ImageField(upload_to='shop/images', default="") def __str__(self): return self.product_name -
Give the default url when a given url is not present in urls.py in template django
I have configured URLs in my database table for dynamic side bar creation. Due to some change in requirement, I have moved some views from a one application to an other application. Because I forgot to change the urls in database, I am getting an error in the application. Adding sample code here custom tag: @register.inclusion_tag('common/sidebar.html', takes_context=True) def show_sidebar(context, active_module_name): request = context['request'] module_list = AppAuthsService.get_user_module_list(user=request.user, active_module_name=active_module_name) return {"modules": module_list} {% if modules %} {%for module in modules %} <li class="nav-item"> <a class="nav-link {{ module.isactive }}" href="{% url module.url %}"> {{module.name}} </a> </li> {% endfor %} {%endif %} Here I want that, it should not break the application. Instead of that there should be optional url argument if urlmatch is not resolved in the {% url module.url %}. -
How to set permission all model table for django
permission:, add , update , delete , views role : like, admin , employee , staff, customer -
Heroku app is live but can't be found on search engines
I've uploaded a Django site using Heroku. It is live on the URL but I can't find it on google, even when I use site: I haven't registered a domain name for it yet, so it's still appname.herokuapp.com. I'm not sure if that's the reason why, as my WordPress site from 4 years ago is quite searchable and it still uses .wordpress.com. Is it because Heroku doesn't allow public sites without a domain registration or maybe Heroku needs us to sign up for subscription plans? Thanks in advanced. -
Will Developer created a Database for storing user and user id under Django?
Some I am designing a bunch of databases for storing bookmarks. I think I will create three of them. User ---- Id Username Tag --- Id Title Description Bookmark -------- Id UserId TagId Title Url I knew Django already create and store users and unique user id when created an account. So normally, do I need to create a whole new database for storing users? -
Why I'm facing thisproblem in python-(django)?
#django Why I cann't migrate.It shows type error:expected string or bytes like object.Why this is showing Can anyone help me to solve this problem? -
Sendgird Web API python example code not working: 401 unauthorized
The problem: Sendgrid web api python example code showing error 401: Unauthorized The settings: server-heroku, framework-django, sendgrid single sender authorized but not domain. Heroku add-on attached. The code: /sendgrid.env:export SENDGRID_API_KEY='the api key' /view.py def Contact(request): message = Mail( from_email='customerservice@shionhouse.net', to_emails='to@example.com', subject='Sending with Twilio SendGrid is Fun', html_content='<strong>and easy to do anywhere, even with Python</strong>') sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) return render(request, 'core/contact.html') By the way, is sendgrid really worth awhile? Or is it just better off using django default SMTP anyway? -
Django test : can authenticate, but not login
I am trying to make a unit test on a rest api. I am using the StaticLiveServerTestCase and so, a temporary in-memory database to make the tests. This needs to have some pre-populated data put in it, this is why I do create a user (which own a "Bristol") in my models. The main thing, I think, is an issue with the authentification : I can authenticate and do a client.login, but it is refused on the API-side :-/ The error I get from the API is a 403=>Invalid username/password, I can't figure out why can I do a client.login and a django.contrib.auth.authenticate, but not passing them in a HTTPBasicAuth (which works in the production server). Something here is to be analysed with the way the "user" is saved in the database. I have seen this question : Django's self.client.login(...) does not work in unit tests where the answer is about a different way to save the password on the database, but it goes back as far as 2015 and it seems that now with django 3 which I am using, the difference disapeared. Here is the code : class test_api(TestCase, StaticLiveServerTestCase): def test_03_get_all_bristol(self): owner_pwd = "pwd" owner, bristol = … -
Django - unable to handle form submission with dynamic field
In my Django form, I have one select field that needs to be populated dynamically based on some information about the current user. I am able to get the field set up correctly and rendered in the form - however, I'm getting an error when submitting the form because it's getting hung up on some of the logic that I have in the form's __init__ method that only makes sense in the context of generating the form in the first place. I'm super-new to Django, and I'm not quite familiar with the design principles for this sort of situation. In my app's admin.py, I have a method that's used for creating a custom view for a data export form - the relevant parts of it are set up like so... # admin.py from organizations.models import Organization from .forms import ExportForm class SomeModelAdmin(SimpleHistoryAdmin, SoftDeletionModelAdmin): def export_view(self, request): authorized_orgs_queryset = Organization.objects.viewable_for_user(request.user).all() authorized_orgs = [{'id': org.id, 'name': org.name} for org in authorized_orgs_queryset] context = dict( self.admin_site.each_context(request), form = ExportForm({'authorized_orgs': authorized_orgs}), ) if request.method == 'POST': form = ExportForm(request.POST) if form.is_valid(): # do some stuff with the form.cleaned_data and return a .csv file as a response return response return TemplateResponse(request, 'export.html', context) So the … -
Django tabular inline show current user as default
Kindly help with below issue. I am stuck from long time. I have two models, media and review Review any media item is reviewed then the review get stored in review model. In admin site I have created tabular inline so that I can see media along with its review, When I click add another review, a new review line is getting added. What I need is by default it should show the Reviewer as current logged in user. Here is the review model, class Review(models.Model): """Represents a review made by an Account on an object """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() review_item = GenericForeignKey('content_type', 'object_id') reviewer = models.ForeignKey( Account, blank=True, null=True, on_delete=models.SET_NULL, help_text="Account of the reviewer", ) RECOMMENDATION_CHOICES = [ ("pending", "pending"), ("accepted", "accepted"), ("declined", "declined"), ] recommendation = models.CharField( max_length=64, choices=RECOMMENDATION_CHOICES, default="pending", help_text="Recommendation of the reviewed object", ) description = models.TextField( blank=True, null=True, help_text="Optional field for reviewer to make comments", ) Here is the admin.py code, class ReviewInline(GenericTabularInline): """Inline for Review models """ model = Review # Limit extra inline forms extra = 1 class MediaAdmin(admin.ModelAdmin): """Admin interface for the Media model """ # *** Form settings *** # Split up the forms into fieldsets fieldsets … -
Django CustomUser model - Two Db Errors
Currently working on a new project: photo blog using custom users. For my user model, I've inherited from AbstractBaseUser with the attributes below. With a top down approach, I've created a custom user (CustomUser) and created two user types using proxy models (Contributor and Producer). Each type then has further attributes using OneToOneFields with CustomUser (located in ContributorMore and ProducerMore, respectively). Relatively straightforward, however I'm consistently running into two issues, second is most important so please take a look! Whenever I update my migrations, I run makemigrations users successfully. However, when subsequently running migrate, I consistently receive the following error: OperationalError: foreign key mismatch - "users_contibutermore" referencing "users_customuser". I can get around this by deleting the migrations folder from my users app, rerunning makemigrations and then migrate - but I have to do this each time I change my model. Any ideas what could be causing this? It has obviously only happened since introducing my ContributorMore and ProducerMore models. However, the code in these must be correct as the migrations run ok when I delete the migrations folder as described. Further, I followed Daniel Feldroy's youtube tutorials on this. The second issue is my recent addition of profile_pics attribute to … -
Why does Django models OneToOne query all objects for drop-down when ForeignKey does not?
models.py class PumpLog(models.Model): # work_order = models.OneToOneField('WorkOrder', on_delete = models.CASCADE) work_order = models.ForeignKey('WorkOrder', on_delete = models.CASCADE) class WorkOrder(models.Model): completed_on = models.DateField('Completed On', null=True, blank=True) template_.html {{ form.work_order|as_crispy_field }} As you can see there is a FK relationship between PumpLog and WorkOrder. When the PumpLog-Update page loads it only queries the selected/related WorkOrder. If the drop-down to select the work order is clicked - it queries additional WorkOrder as the user scrolls or searches. I am trying to convert it to OneToOne. But when I switch it to OneToOne I notice that it retrieves all WorkOrders - which can take 1-4 minutes to load. I noticed this by placing print(self.index) in the WorkOrder's __str__ method. In the console I see it list every single WorkOrder one-by-one. But if I switch it back to FK it only displays the index of the one already selected in the drop-down. This doesn't seem to be a widget or crispy_form issue because I see the same behavior when I remove or revert those. I understand to some degree that it needs access to all of the work orders so that the user can select whichever one. BUT it doesn't seem to need to load all … -
Django model instance from queryset not updating on save()
I have the following code VocabFromDatabase = Vocab.objects.filter(User = U, IsCard = True).order_by("LastStudyDate") VocabFromDatabase[0].Mnem = "Passed" VocabFromDatabase[0].save() According the docs save() should save the changes, but it seems to silently fail. After some fiddling around it seems the problem isn't with save() but rather with assigning a value to a property of one of the objects from the queryset. However everywhere I look tells me to either use update() (which I think would update all the objects in the queryset, which I do not want), or that save() should work. Is there something I'm not aware of, or something I'm doing wrong here? -
What does Django's Exception class' "code" argument do?
I read that: Provide a descriptive error code to the constructor: # Good ValidationError(_('Invalid value'), code='invalid') # Bad ValidationError(_('Invalid value')) from this page: https://docs.djangoproject.com/en/3.1/ref/forms/validation/#raising-validationerror However, I cannot find what the code= parameter is used for. I was able to find an example use case here: https://www.fullstackpython.com/django-forms-validationerror-examples.html with: raise ValidationError( error, code="InvalidSql" ) raise django.forms.ValidationError( _('Date must be later than %(date)s.') % {'date': min_value.strftime('%m/%d/%Y'), }, code='minimum') That's about the only time I've seen code= used but I still can't figure out why it is useful and where it comes into play. -
How can I do to test the method save from a Model?
I have this model : class Team(models.Model): user = models.CharField(max_length=250, default="default", null=True) def __str__(self): return self.user And I would like to do a unittest for the save. I have that : class TeamModelTest(TestCase): @classmethod def setUpTestData(cls): Team.objects.create(user='Peter') def test_save(self): team = Team() team.user = 'Bruce' team.save() But the problem is how can I do to test a function which return nothing ? Could you help me please ? Thank you very much ! -
Static folder django
I just created a django application, and I have a problem that I cannot resolve. I have 1 css file 'root.css' that I would like to link with my html database but it's like this /static/root.css was completely ignored. I arrive mostly at link /static/home/home.css on my home app. This is not work (/templates/base.html) : {% load static %} <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr-FR" lang="fr-FR"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> <link rel="stylesheet" type="text/css" ref="{% static 'root.css' %}"> **// Not work** {% block css %} {% endblock %} <title>Learned</title> </head> <body> {% block content %} {% endblock %} </body> </html> This is work (/home/templates.home.html) : {% block css %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'home/home.css' %}"> {% endblock %} In my settings.py : STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] -
My uploaded files are not saved to the Database
my model class FactuurBestanden(models.Model): file = models.FileField(upload_to='profile_pics') my form class FactuurBestandenForm(forms.ModelForm): class Meta: model = FactuurBestanden fields = '__all__' my view def createFacturenAdmin(request): if request.user.is_superuser: if request.method == "POST": form = FactuurBestandenForm(request.POST) if form.is_valid(): form.save() else: print("form not valid") return redirect("facturatie_admin") form = FactuurBestandenForm() return render(request, 'users/admin_facturatie.html', {'form':form}) and my template <form method="post"> {% csrf_token %} {{ form.as_p }} <button style="margin-left: 40px" class="Button1" type="submit">Click here</button> </form> The uploaded files are not saved to the DB ? what am i doing wrong here. -
Unable to POST the data using rest Django - NOT NULL constraint failed: author_id
I have the following error, and I guess the problem with how can I add the author id to the post automatically. And also I tried to add null=True author = models.ForeignKey(User, null=True, blank=True) The error disappeared! but unfortunately, the author id is still null!!! Please I'm a new developer in Django. IntegrityError at /auctions/api/addAuction/ NOT NULL constraint failed: auctions_auction.author_id Request Method: POST Request URL: http://127.0.0.1:8000/auctions/api/addAuction/ Django Version: 3.1.5 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: auctions_auction.author_id /auctions/api/serializers.py class AddAuctionsSerializer(serializers.ModelSerializer): print("AddA uctionsSerializer Function call") class Meta: model = Auction # Get the current user from request context def validate_author(self, value): return self.context['request'].user author_id = serializers.Field(source='author.id') fields = ["title", "desc", "image","location","min_value","date_added","author_id"] read_only_fields = ('author','id','author_id','author.id') /auctions/api/view.py class addAuction(APIView): #permission_classes = [permissions.IsAuthenticated] #authentication_classes = [SessionAuthentication, BasicAuthentication] def pre_save(self, obj): obj.owner = self.request.user def post(self, request, format=None): auction = Auction() auction.author = request.user serializer = AddAuctionsSerializer(data=request.data) print(serializer) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) /auctions/api/url.py``` path('addAuction/', addAuction.as_view()), /auctions/model.py class Auction(models.Model): location = LocationField() author = models.ForeignKey(User, on_delete=models.CASCADE,null=False) # author = models.ForeignKey(User, null=True, blank=True) title = models.CharField(max_length=300) desc = models.CharField(max_length=2000, blank=True) image = models.ImageField(upload_to='auction_images/', blank=True, default = 'auction_images/default/default.svg') min_value = models.IntegerField() #date_added = models.DateTimeField() date_added = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) winner … -
Django runserver is working but website isn't loading on other port than 8080: CPANEL
I have two projects of Django, I am using the Cpanel terminal to host this at 8080(WORKING),8083(NOT WORKING) I am using the Cpanel terminal to host the Django website at port 8083 Now I tried this python manage.py runserver 0.0.0.0:8083 It is working and the server started at 0.0.0.0:8083 Now this should be visible to us in the browser using our websiteIP:8083 But this isn't working. The port 8083 website isn't loading but port 8080 I have checked ALLOWED HOST =["my.IP.241.0","my_website_url.com"] in settings.py -
Django Template - Unable To Modify Jekyll Carousel Script
I'm using the Jekyll framework and using the official Carousel script from their website (https://jekyllcodex.org/without-plugin/slider/) and I'm struggling to figure out how to make it possible to pass a name to the carousel.html script so that I can setup multiple carousels using the same script. My goal is to be able to just use: {% include carousel.html name="CatImages" height="20" unit="%" duration="7" %} and it should be able to simply receive the images from a carousel.yml file that looks similar to: ` CatImages: - /assets/img/cat1.png - /assets/img/cat2.png I've tried to append the string to the variable name, which works but gives me a slightly different output - one that I can't figure out the type of. The resulting variable coming from {{site.data.carousel.{{ include.name }}}} returns {"CatImages"=>["/assets/img/cat1.png", "/assets/img/cat2.png"]} and when running through the for loops it returns the image paths as one whole string. For example, this: {% for item in images %} {{item}} {% endfor %} returns: images/assets/img/cat1.png/assets/img/cat2.png But overall, I don't understand what the variable is and I can't figure it out from googling. I'm new to Django templates, but for the life of me I can't figure out what the {""=>["",""]} notation is. Any pointers or tips would be … -
CONSOLE ERROR: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I am trying to receive a data from form in HTML, I added javascript to add EventListener and convert the data into json format var form = document.getElementById('form') csrftoken = form.getElementsByTagName("input")[0].value console.log("Newtoken:", form.getElementsByTagName("input")[0].value) form.addEventListener('submit', function(e){ e.preventDefault() console.log('Form submitted') submitFormData() }) function submitFormData(){ console.log('Add button clicked') var itemInfo = { 'item_name':form.item_name.value, 'item_quantity':form.item_quantity.value, 'item_status':form.item_status.value, 'date':form.date.value, } console.log('Item Info:', itemInfo) var url = '/add_item/' fetch(url,{ method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'item':itemInfo}) }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); window.location.href = "{% url 'listview' %}" }) } But I keep getting this console error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise.then (async) submitFormData @ (index):75 (anonymous) @ (index):51 -
how can i pre set author by user with helper crispy inlineformset_factory django?
guys. First fo all, thanks for any helpers. I have started learning Django a few months. So, I am trying to set author with the logged user. I have spent long hours looking up for... But up to now I didn't have successful. models.py class Painel(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) hashtag = models.CharField(max_length=255, unique=True, blank=False, null=True) painel_date_posted = models.DateTimeField(auto_now_add= True, null=True) painel_date_updated = models.DateTimeField(auto_now= True, null=True) def __str__(self): return self.hashtag def get_absolute_url(self): return reverse('painel-detail', kwargs={'hashtag': self.hashtag}) class Post(models.Model): #=============================================================================== author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) painel = models.ForeignKey(Painel, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100, blank=False) slug = models.SlugField(max_length=100 ,null=True) #=============================================================================== content = models.TextField(null=True, help_text='Write your Post', blank=False) url = models.URLField(help_text='Paste here the link, witch you saw that news?', blank=False) contact_number = models.CharField(max_length=20,blank=True, help_text='If you have another way to comunicate.') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) form.py class PainelForm(ModelForm): class Meta: model = Painel fields = ('hashtag', 'created_by', ) @property def helper(self, *args, **kwargs): helper = FormHelper() helper.form_tag = False # This is crucial. helper.layout = Layout( Fieldset('Create new Painel - {{ user|capfirst }}', PrependedText('hashtag','#', placeholder="hashtag"), ), ) return helper class PostFormHelper(FormHelper): def __init__(self, *args, **kwargs): super(PostFormHelper, self).__init__(*args, **kwargs) self.form_tag = False # This is … -
Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? in Django
I'm getting this error while trying to run: docker-compose run app python manage.py migrate with Django. this is the docker-compose.yml: version: '3' volumes: database: { } services: app: build: context: . dockerfile: ./docker/app/dev/Dockerfile depends_on: - postgres volumes: - ./app:/app:z env_file: - ./.envs/.dev/.app - ./.envs/.dev/.postgres ports: - "8000:8000" command: "python manage.py runserver 0.0.0.0:8000" postgres: image: "postgres:13.1" volumes: - database:/var/lib/postgresql/data:Z env_file: - ./.envs/.dev/.postgres environment: - POSTGRES_HOST_AUTH_METHOD=trust ports: - "5432:5432" I don't know why I'm getting this error. PostgreSQL is running correctly and all the settings are appropiately configured. This is the full traceback error:. Traceback (most recent call last): File "/app/manage.py", line 7, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 216, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File … -
how to get a string parametr in drf modelviewset
i need to use a path with an optional paramentr, to specify a user via a srting a request would look like 'api/users/specific_username' or 'api/users' for all users urls: router = DefaultRouter() router.register(r'users', MyUserViewSet, basename='user-me') views: `class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self): queryset = User.objects.all() if self.kwargs['username']: username=self.request.GET.get('username') queryset = User.objects.filter(username=username) return queryset` username=self.kwargs['username'] returns KeyError username=self.request.GET.get('username') returns None